[英]Parse the JSON Response in C#
對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結果做兩件事(我將其保存為字符串*):
處理那些字符串。
轉換為字符串:我使用以下方法做到了:
var reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
如何實現呢?
您可以將JSON解析為具體的類,然后再使用這些類。
為此,您可以使用json2csharp之類的服務,該服務根據您提供的JSON生成類。 另外,您可以使用Visual Studio內置功能將JSON粘貼為類 :
public class Alternative
{
public double confidence { get; set; }
public string transcript { get; set; }
}
public class Result
{
public List<Alternative> alternatives { get; set; }
public bool final { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
public int result_index { get; set; }
}
然后,您可以使用JSON.NET將字符串化的JSON解析為具體的類實例:
var root = JsonConvert.DeserializeObject<RootObject>(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<MyRootObject>(responseFromServer);
並像處理其他任何.NET對象一樣處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.