使用c#中的JSON.PARSE或REGEX获得JSON响应的单行



我是一个初级Java开发人员,而对于C#不太好,因此我希望解决问题。我要做的是使用GITHUB上共享的现有代码,该代码使用麦克风输入,将其上传到Google语音到文本API,然后用成绩单返回JSON响应。这部分都可以正常工作。

什么不起作用,正在将"成绩单:"的值存储在JSON中的字符串变量中。

我尝试过多种方式,我已经寻找了使用SimpleJson和Newtonsoft将JSON响应转换为对象的方法,并且我还尝试使用正则表达式来读取以"成绩单开头"的JSON线。"我看到了我想做的事情的示例(下面链接),但是我遇到了编译器错误。如果有人可以帮助我,或者将我指出更好的结果,我会很感激。

这是我正在使用的代码。

//从https://github.com/steelejay/lowkeyspeech

获得
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Web;

[RequireComponent(typeof(AudioSource))]
public class GoogleVoiceSpeech : MonoBehaviour {
    public GUIText TextBox;
    struct ClipData {
        public int samples;
    }
    const int HEADER_SIZE = 44;
    private int minFreq;
    private int maxFreq;
    private bool micConnected = false;
    //A handle to the attached AudioSource
    private AudioSource goAudioSource;
    public string apiKey;
    // Use this for initialization
    void Start() {
        //Check if there is at least one microphone connected
        if (Microphone.devices.Length <= 0) {
            //Throw a warning message at the console if there isn't
            Debug.LogWarning("Microphone not connected!");
        } else //At least one microphone is present
          {
            //Set 'micConnected' to true
            micConnected = true;
            //Get the default microphone recording capabilities
            Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);
            //According to the documentation, if minFreq and maxFreq are zero, the microphone supports any frequency...
            if (minFreq == 0 && maxFreq == 0) {
                //...meaning 44100 Hz can be used as the recording sampling rate
                maxFreq = 44100;
            }
            //Get the attached AudioSource component
            goAudioSource = this.GetComponent<AudioSource>();
        }
    }
    void OnGUI() {
        //If there is a microphone
        if (micConnected) {
            //If the audio from any microphone isn't being recorded
            if (!Microphone.IsRecording(null)) {
                //Case the 'Record' button gets pressed
                if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Record")) {
                    //Start recording and store the audio captured from the microphone at the AudioClip in the AudioSource
                    goAudioSource.clip = Microphone.Start(null, true, 7, maxFreq); //Currently set for a 7 second clip
                }
            } else //Recording is in progress
              {
                //Case the 'Stop and Play' button gets pressed
                if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Stop and Play!")) {
                    float filenameRand = UnityEngine.Random.Range(0.0f, 10.0f);
                    string filename = "testing" + filenameRand;
                    Microphone.End(null); //Stop the audio recording
                    Debug.Log("Recording Stopped");
                    if (!filename.ToLower().EndsWith(".wav")) {
                        filename += ".wav";
                    }
                    var filePath = Path.Combine("testing/", filename);
                    filePath = Path.Combine(Application.persistentDataPath, filePath);
                    Debug.Log("Created filepath string: " + filePath);
                    // Make sure directory exists if user is saving to sub dir.
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    SavWav.Save(filePath, goAudioSource.clip); //Save a temporary Wav File
                    Debug.Log("Saving @ " + filePath);
                    //Insert your API KEY here.
                    string apiURL = "https://speech.googleapis.com/v1/speech:recognize?&key=AIzaSyAV65cThBBZAqmzW7MbWaccybtBrwY4Udc";
                    string Response;
                    Debug.Log("Uploading " + filePath);
                    Response = HttpUploadFile(apiURL, filePath, "file", "audio/wav; rate=44100");
                    Debug.Log("Response String: " + Response);
                    var jsonresponse = SimpleJSON.JSON.Parse(Response);
                    if (jsonresponse != null) {
                        string resultString = jsonresponse["result"][0].ToString();
                        var jsonResults = SimpleJSON.JSON.Parse(resultString);
                        string transcripts = jsonResults["alternative"][0]["transcript"].ToString();
                        Debug.Log("transcript string: " + transcripts);
                        TextBox.text = transcripts;
                    }
                    //goAudioSource.Play(); //Playback the recorded audio
                    File.Delete(filePath); //Delete the Temporary Wav file
                }
                GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 25, 200, 50), "Recording in progress...");
            }
        } else // No microphone
          {
            //Print a red "Microphone not connected!" message at the center of the screen
            GUI.contentColor = Color.red;
            GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Microphone not connected!");
        }
    }
    public string HttpUploadFile(string url, string file, string paramName, string contentType) {
        System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
        Debug.Log(string.Format("Uploading {0} to {1}", file, url));
        Byte[] bytes = File.ReadAllBytes(file);
        String file64 = Convert.ToBase64String(bytes,
                                         Base64FormattingOptions.None);
        Debug.Log(file64);
        try {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {


                string json = "{ "config": { "languageCode" : "en-US" }, "audio" : { "content" : "" + file64 + ""}}";
                Debug.Log(json);
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Debug.Log(httpResponse);
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
                var result = streamReader.ReadToEnd();
                Debug.Log("Response:" + result);
            }
        }
        catch (WebException ex) {
            var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
            Debug.Log(resp);
        }

        return "empty";
    }
}

我正在通过JSON结果恢复正确的控制台消息。我只需要将"成绩单"值将其放入字符串中。这是Google API的响应示例。

Response:{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "this is a test",
          "confidence": 0.98762906
        }
      ]
    }
  ]
}

SimpleJson框架的实际创建者对几年前有类似问题的人做出了回应,但是当我尝试实现类似的解决方案时,我会发现错误,因为我的响应是单数。

https://answers.unity.com/questions/1443367/get-json-array-aray-object-string-value.html

我感谢任何人的帮助或指导。我一直在网上寻找几天的时间,试图让这项工作工作,并问同事(由于他们对C#的经验不足,他们在此之前都无法帮助我。

newtonsoft是一个更好的选择,我会带您了解如何使用它。

首先,创建您需要保留解析结果的C#类。在您的示例中,它们看起来像这样:

public class SpeechResponse
{
    public Result[] results { get; set; }
}
public class Result
{
    public Alternative[] alternatives { get; set; }
}
public class Alternative
{
    public string transcript { get; set; }
    public float confidence { get; set; }
}

您已经知道如何获取JSON数据,因此假设它已保存在String json中。您可以使用此命令将字符串变成C#类:

var response = JsonConvert.DeserializeObject<SpeechResponse>( json );

和您要查找的特定数据可以得到这样的获取:

string phrase = response.results[0].alternatives[0].transcript;

奖励提示
如果您使用的是Visual Studio,则可以通过复制JSON示例数据并选择"编辑 -> paste special-> past json作为类"(阅读更多)。

最新更新