使用Newtonsoft.Json.Linq

时间:2017-02-03 10:58:04

标签: c# json linq json.net google-speech-api

我正在尝试将谷歌语音的结果解析为文本API。 json的回应是:

{"result":[]}
{"result":[
          {"alternative":[
                         {"transcript":"hello Google how are you     feeling","confidence":0.96274596},
                         {"transcript":"hello Google how are you today","confidence":0.97388196},
                         {"transcript":"hello Google how are you picking","confidence":0.97388196},
                         {"transcript":"hello Google how are you kidding","confidence":0.97388196}
                         ]
         ,"final":true}]
,"result_index":0
}

现在我试图通过JObject解析它。解析出现两次的Result对象时会出现问题,如何解析第二个Result对象。这是我正在尝试的代码:

              StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
              Console.WriteLine(SR_Response.ReadToEnd()+SR_Response.ToString());
              String json_response = SR_Response.ReadToEnd() + SR_Response.ToString();
              JObject joo = JObject.Parse(json_response);
              JArray ja = (JArray)joo["result"];

                        foreach (JObject o in ja)
                        {
                            JArray ja2 = (JArray)o["alternative"];
                            foreach (JObject h in ja2)
                            {
                                Console.WriteLine(h["transcript"]);
                            }
                        }

我尝试使用反序列化对象代码的下一个解决方案是:

                string responseFromServer = (SR_Response.ReadToEnd());
                String[] jsons = responseFromServer.Split('\n');
                String text = "";
                foreach (String j in jsons)
                {
                    dynamic jsonObject = JsonConvert.DeserializeObject(j);
                    if (jsonObject == null || jsonObject.result.Count <= 0)
                    {
                        continue;
                    }
                    Console.WriteLine((string)jsonObject["result"]["alternative"][0]["transcript"]);
                    text = jsonObject.result[0].alternative[0].transcript;
                }
                Console.WriteLine("MESSAGE : "+text); 

1 个答案:

答案 0 :(得分:0)

您拥有的是一系列JSON根对象连接在一起成为一个流。如cppreference中所述,可以通过设置Read Multiple Fragments With JsonReader来反序列化此类流。因此,要反序列化您的流,您应该首先介绍以下扩展方法:

<div class="toggler">
  <i class="fa fa-toggle-off fa-2x inactive my-button"></i>
</div> 

接下来,使用代码生成实用程序(如JsonReader.SupportMultipleContent = true)为单个JSON根对象生成c#类,如下所示:

public static class JsonExtensions
{
    public static IEnumerable<T> DeserializeObjects<T>(Stream stream, JsonSerializerSettings settings = null)
    {
        var reader = new StreamReader(stream); // Caller should dispose
        return DeserializeObjects<T>(reader, settings);
    }

    public static IEnumerable<T> DeserializeObjects<T>(TextReader textReader, JsonSerializerSettings settings = null)
    {
        var ser = JsonSerializer.CreateDefault(settings);
        var reader = new JsonTextReader(textReader); // Caller should dispose

        reader.SupportMultipleContent = true;

        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.None || reader.TokenType == JsonToken.Undefined || reader.TokenType == JsonToken.Comment)
                continue;
            yield return ser.Deserialize<T>(reader);
        }
    }
}

反序列化如下:

public class Alternative
{
    public string transcript { get; set; }
    public double confidence { get; set; }
}

public class Result
{
    public List<Alternative> alternative { get; set; }
    public bool final { get; set; }
}

public class RootObject
{
    public List<Result> result { get; set; }
    public int result_index { get; set; }
}

完成此操作后,您可以使用标准c#编程技术(例如http://json2csharp.com/)来枚举List<RootObject> results; using (var stream = HWR_Response.GetResonseStream()) { results = JsonExtensions.DeserializeObjects<RootObject>(stream).ToList(); } 值,例如:

transcript

如果您不想为JSON集合定义固定数据模型,可以直接反序列化为var transcripts = results .SelectMany(r => r.result) .SelectMany(r => r.alternative) .Select(a => a.transcript) .ToList(); 列表,如下所示:

JObject

然后,您可以使用Linq选择嵌套在每个对象中的所有List<JObject> objs; using (var stream = HWR_Response.GetResonseStream()) { objs = JsonExtensions.DeserializeObjects<JObject>(stream).ToList(); } 属性的值:

"transcript"

更新了显示两个选项的示例SelectTokens()