【问题标题】:Convert JSON response stream to string将 JSON 响应流转换为字符串
【发布时间】:2012-10-14 01:34:15
【问题描述】:

我正在尝试进行 POST,然后将 JSON 响应读入字符串。

我认为我的问题是我需要将自己的对象传递给 DataContractJsonSerializer,但我想知道是否有某种方法可以将响应转换为关联数组或某种键/值格式。

我的 JSON 格式如下:{"license":"AAAA-AAAA-AAAA-AAAA"} 我的代码如下:

using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email)))
{
   string output = new StreamReader(response).ReadToEnd();
   response.Close();

   DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string));
   MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
   string results = json.ReadObject(ms) as string;

   licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null);
}

【问题讨论】:

  • Newtonsoft JSON 可以反序列化为 Dictionary .. 并且可以很容易地导航。

标签: c# .net json


【解决方案1】:

我强烈建议您研究一下 Newtonsoft.Json:

http://james.newtonking.com/pages/json-net.aspx

NuGet:https://www.nuget.org/packages/newtonsoft.json/

添加对项目的引用后,您只需在文件顶部包含以下using

using Newtonsoft.Json.Linq;

然后在你的方法中你可以使用:

var request= (HttpWebRequest)WebRequest.Create("www.example.com/ex.json");
var response = (HttpWebResponse)request.GetResponse();
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();

var json = JObject.Parse(rawJson);  //Turns your raw string into a key value lookup
string license_value = json["license"].ToObject<string>();

【讨论】:

  • 我确信其他响应有效,但这让我得到了我想要去的地方。此外,我自己安装 JSON NET dll 并导致错误,我强烈建议在 Visual Studio 中使用 NUGET 安装程序扩展。
【解决方案2】:

你可以用字典来做这样的事情

Dictionary<string, string> values = 
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

如果你已经知道你的对象,或者类似的东西

var yourobject = JsonConvert.DeserializeObject<YourObject>(json);

用这个工具

http://james.newtonking.com/projects/json/help/

参考这里 Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2020-12-19
    • 2017-01-17
    • 2022-11-19
    • 1970-01-01
    • 2015-03-01
    • 2016-07-30
    相关资源
    最近更新 更多