将JSON响应流转换为字符串

时间:2012-10-24 01:59:02

标签: c# .net json

我正在尝试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);
}

谢谢!

2 个答案:

答案 0 :(得分:17)

我强烈建议您查看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>();

答案 1 :(得分:1)

你可以使用字典

做这样的事情
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

相关问题