繁体   English   中英

在C#中解析JSON响应

[英]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结果做两件事(我将其保存为字符串*):

  1. 获取json响应的笔录部分。
  2. 处理那些字符串。

    • 我是新来的。 转换为字符串仅称为序列化。 为什么反序列化在这里有帮助?

转换为字符串:我使用以下方法做到了:

 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.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对象一样处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM