2016-06-25 51 views
0

在对api进行查询后,我得到一个json响应。解析C#中的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结果(我把它作为一个字符串*):

  1. 获取的成绩单部(S) JSON响应。
  2. 处理这些字符串。

    • 我对此很陌生。转换为字符串只能称为序列化。为什么反序列化会在这里起作用?

转换为字符串:我做到了使用:

var reader = new StreamReader(response.GetResponseStream()); 


      responseFromServer = reader.ReadToEnd(); 

如何实现这一目标?

+0

有没有需要反序列化 - 但它会让你的生活更轻松:o) –

+0

反序列化JSON将它转换回.NET对象。然后,您可以访问该对象的属性,而不是进行一堆字符串解析。使用像Newtonsoft JSON.NET这样的库来帮助反序列化。 – wablab

回答

1

你应该反序列化这个。这是处理它的最简单的方法。使用Json.NETdynamic可能看起来像:

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对象。

+2

使用剪贴板中的JSON VS提供菜单编辑/粘贴特殊/粘贴JSON作为类 –

3

您可以将JSON解析为具体的类并在之后使用。

为此,您可以使用像json2csharp这样的服务,它根据您提供的JSON生成类。或者,您可以使用Visual Studio内置功能粘贴JSON如类

enter image description here

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);