Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检索json WebResponse c中的特定行#_C#_Json - Fatal编程技术网

C# 检索json WebResponse c中的特定行#

C# 检索json WebResponse c中的特定行#,c#,json,C#,Json,我正试图通过WebResponse方法检索json请求中的特定行,但目前无法实现。我正在将wav文件音频转换为文本。它工作得很好,转换也很好,但我得到了输出行:识别状态、持续时间、显示、偏移量。我想要输出到文本框的唯一一行是“Display”行,其中音频转换为文本 json格式如下所示,我尝试只获取“Display”行 { "RecognitionStatus": "Success", "Offset": 22500000, "Duration": 21000000, "NBes

我正试图通过WebResponse方法检索json请求中的特定行,但目前无法实现。我正在将wav文件音频转换为文本。它工作得很好,转换也很好,但我得到了输出行:识别状态、持续时间、显示、偏移量。我想要输出到文本框的唯一一行是“Display”行,其中音频转换为文本

json格式如下所示,我尝试只获取“Display”行

{
  "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,为什么不尝试使用 的反序列化方法。它将允许您从响应中访问特定属性。 您可以使用它从json字符串中获取对象


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

因为
NBest
将是一个集合。您必须迭代以获得
显示的每个值

您可以检索
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
{
公共字符串识别状态{get;set;}
公共整数偏移量{get;set;}
公共整数持续时间{get;set;}
公共列表NBest{get;set;}
}
公共类Nbest
{
公共浮动置信度{get;set;}
公共字符串词法{get;set;}
公共字符串ITN{get;set;}
公共字符串MaskedITN{get;set;}
公共字符串显示{get;set;}
}
输出:


无需反序列化为自定义类型,即可使用本机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"]);
}

法赞的回答很贴切,它会给你你想要的。 但是,如果您不想麻烦创建一个对象来反序列化您的响应。同样,您可以使用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"];
}
使用(StreamReader sr=newstreamreader(response.GetResponseStream())
{
ResponseString=sr.ReadToEnd();
JavaScriptSerializer js=新的JavaScriptSerializer();
动态对象=js.反序列化(ResponseString);
textBox1.Text=obj[“NBest”][0][“Display”];
}

Json.Net比
JavaScriptSerializer
更受欢迎,请尝试使用它?是的,我正在查看它,但不知道如何检索特定的行。如果在
NBest
中只有一个项目,请使用
obj.NBest[0]。显示
否则循环通过
NBest
谢谢!obj.DisplayText;成功了
JavaScriptSerializer
还提供对属性的访问。他只需要使用obj.NBest[index]来获取特定的记录。嘿,我试过了,但它没有只输出“Display”。它的输出与以前相同。我的对象类如下所示。公共类MyObject{publicstringdisplaytext;}我不知道这是否正确,因为它与webresponse没有任何联系ever@Weirdrandom你能分享你试图反序列化这个JSON的类吗?嘿,是的,它现在起作用了。我刚刚做了obj.DisplayText,它成功了!:D