在C#中解析JSON响应
在对api进行查询后,我得到了一个json响应。
JSON就像:
{ "results": [ { "alternatives": [ { "confidence": 0.965, "transcript": "how do I raise the self esteem of a child in his academic achievement at the same time " } ], "final": true }, { "alternatives": [ { "confidence": 0.919, "transcript": "it's not me out of ten years of pseudo teaching and helped me realize " } ], "final": true }, { "alternatives": [ { "confidence": 0.687, "transcript": "is so powerful that it can turn bad morals the good you can turn awful practice and the powerful once they can teams men and transform them into angel " } ], "final": true }, { "alternatives": [ { "confidence": 0.278, "transcript": "you know if not on purpose Arteaga Williams who got in my mother " } ], "final": true }, { "alternatives": [ { "confidence": 0.621, "transcript": "for what pink you very much " } ], "final": true } ], "result_index": 0 }
我必须对上面的json结果做两件事(我把它保存为字符串*):
- 获取json响应的成绩单部分。
-
处理这些字符串。
- 我是新来的。 转换为字符串仅称为序列化。 为什么反序列化有助于此?
转换为字符串:我使用以下方法完成:
var reader = new StreamReader(response.GetResponseStream()); responseFromServer = reader.ReadToEnd();
怎么做到这一点?
您可以将JSON解析为具体类,并在以后使用它们。
为此,您可以使用json2csharp之类的服务,该服务根据您提供的JSON生成类。 或者,您可以使用Visual Studio内置function粘贴JSON作为类 :
public class Alternative { public double confidence { get; set; } public string transcript { get; set; } } public class Result { public List alternatives { get; set; } public bool final { get; set; } } public class RootObject { public List results { get; set; } public int result_index { get; set; } }
然后,您可以使用JSON.NET将字符串化的JSON解析为具体的类实例:
var root = JsonConvert.DeserializeObject(responseFromServer);
你应该反序列化这个。 这是处理它的最简单方法。 使用Json.NET和dynamic
可能看起来像:
dynamic jsonObj = JsonConvert.DeserializeObject(responseFromServer); foreach (var result in jsonObj.results) { foreach (var alternative in result.alternatives) { Console.WriteLine(alternative.transcript); } }
但您可能希望为它创建显式类。 然后你可以这样做:
MyRootObject root = JsonConvert.DeserializeObject(responseFromServer);
像任何其他.NET对象一样处理它。