【问题标题】:Retrieve specific row in json WebResponse c#检索json WebResponse c#中的特定行
【发布时间】:2018-02-25 03:38:26
【问题描述】:

我正在尝试通过 WebResponse 方法检索 json 请求中的特定行,但目前没有成功。我正在将 wav 文件音频转换为文本。它工作得很好并且转换得很好,但我得到了输出行:RecognitionStatus、Duration、Display、Offset。我想要输出到文本框的唯一行是音频到文本转换到的“显示”行。

json 格式看起来像这样,我试图只获取“显示”行。

{
  "RecognitionStatus": "Success",
  "Offset": 22500000,
  "Duration": 21000000,
  "NBest": [{
    "Confidence": 0.941552162,
    "Lexical": "find a funny movie to watch",
    "ITN": "find a funny movie to watch",
    "MaskedITN": "find a funny movie to watch",
    "Display": "Find a funny movie to watch."
  }]
}

这是我目前的代码。

        HttpWebRequest request = null;
        string ResponseString;
        request = (HttpWebRequest)HttpWebRequest.Create("https://speech.platform.bing.com/speech/recognition/dictation/cognitiveservices/v1?language=en-US&format=simple");
        request.SendChunked = true;
        request.Accept = @"application/json;text/xml";
        request.Method = "POST";
        request.ProtocolVersion = HttpVersion.Version11;
        request.ContentType = @"audio/wav; codec=audio/pcm; samplerate=16000";
        request.Headers["Ocp-Apim-Subscription-Key"] = "hidden";

        using (FileStream fs = new FileStream(@"G:\Microsoft Visual Studio Projects\SpeechRecognitionFormsTestUpdaterad\SpeechRecognitionForms\bin\Debug\Logs\log 24-2.wav", FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = null;
            int bytesRead = 0;
            using (Stream requestStream = request.GetRequestStream())
            {
                /*
                * Read 1024 raw bytes from the input audio file.
                */

                buffer = new Byte[checked((uint)Math.Min(1024, (int)fs.Length))];
                while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                // Flush
                requestStream.Flush();
            }
        }
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                ResponseString = sr.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                MyObject obj = (MyObject)js.Deserialize(ResponseString, typeof(MyObject));
                textBox1.Text = ResponseString;
            }
            //textBox1.Text = ResponseString;
        }

【问题讨论】:

  • Json.Net 比JavaScriptSerializer 更受欢迎,尝试使用它吗?
  • 是的,我正在查看它,但只是不知道如何检索该特定行。
  • 如果NBest 中只有一个项目,请使用obj.NBest[0].Display,否则循环通过NBest
  • 谢谢! obj.DisplayText;工作!

标签: c# json


【解决方案1】:

NBest 将是一个集合。您必须迭代以获取 Display 的每个值。

你可以像这样检索Display的值:

using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    ResponseString = sr.ReadToEnd();
    JavaScriptSerializer js = new JavaScriptSerializer();
    MyObject obj = (MyObject)js.Deserialize(ResponseString, typeof(MyObject));
    textBox1.Text = ResponseString;
    foreach (var nb in obj.NBest)
    {
        Console.WriteLine(nb.Display);
    }
}

或者,如果你总是得到一个 NBest 对象,你可以像这样检索它:

if (obj.NBest.Count == 1)
{
    string display = obj.NBest[0].Display;
}

更新:

以下是我将 OP 的 JSON 反序列化为的类:

public class MyObject
{
    public string RecognitionStatus { get; set; }
    public int Offset { get; set; }
    public int Duration { get; set; }
    public List<Nbest> NBest { get; set; }
}

public class Nbest
{
    public float Confidence { get; set; }
    public string Lexical { get; set; }
    public string ITN { get; set; }
    public string MaskedITN { get; set; }
    public string Display { get; set; }
}

输出:

【讨论】:

  • 嘿,我试过了,但它只输出“显示”。它的输出与以前相同。我的对象类看起来像这样。公共类 MyObject { 公共字符串 DisplayText;我不知道这是否正确,因为它与 webresponse 没有任何联系
  • @Weirdrandom 你能分享你试图反序列化这个 JSON 的类吗?
  • 嘿! ,是的,它现在起作用了。我刚刚做了 obj.DisplayText 并且成功了! :D
【解决方案2】:

无需反序列化为自定义类型,您就可以使用本机 JSON.Net 对象:

string thejson = @"
{
  ""RecognitionStatus"": ""Success"",
  ""Offset"": 22500000,
  ""Duration"": 21000000,
  ""NBest"": [{
    ""Confidence"": 0.941552162,
    ""Lexical"": ""find a funny movie to watch"",
    ""ITN"": ""find a funny movie to watch"",
    ""MaskedITN"": ""find a funny movie to watch"",
    ""Display"": ""Find a funny movie to watch.""
  }]
}";

var jobj = JObject.Parse(thejson);
JArray arr = jobj["NBest"] as JArray;
foreach (JToken jt in arr)
{
    Console.WriteLine(jt["Display"]);
}

【讨论】:

    【解决方案3】:

    由于您的响应只是 json,为什么不尝试使用将其转换为反序列化对象 Newtonsoft.Json 的反序列化方法。它将使您可以从响应中访问特定属性。 你可以使用这个JsonToC#,它会给你来自json字符串的对象。

    或者只是obj.NBest[index]会给你具体的记录。

    【讨论】:

    • JavaScriptSerializer 还提供对属性的访问权限。
    • 他只需要使用obj.N Best[index] 来获取具体的记录。
    【解决方案4】:

    Faizan 的回答很中肯,它会给你你想要的。 但是,如果您不想为创建一个对象来反序列化您的响应而烦恼。您也可以使用 dynamic 关键字,同样:

    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        ResponseString = sr.ReadToEnd();
        JavaScriptSerializer js = new JavaScriptSerializer();
        dynamic obj = js.Deserialize<dynamic>(ResponseString);
        textBox1.Text = obj["NBest"][0]["Display"];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多