Parse the JSON Response in C#

后端 未结 2 1502
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 14:58

I get a json response after making a query to an api.

The JSON is like:

    {
   \"results\": [
      {
         \"alternatives\": [
            {
           


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-07 15:30

    You should deserialize this. It's the easiest way to deal with it. Using Json.NET and dynamic that might look like:

    dynamic jsonObj = JsonConvert.DeserializeObject(responseFromServer);
    foreach (var result in jsonObj.results) {
        foreach (var alternative in result.alternatives) {
            Console.WriteLine(alternative.transcript);
        }
    }
    

    But you might want to make explicit classes for it instead. Then you can do:

    MyRootObject root = JsonConvert.DeserializeObject(responseFromServer);
    

    And deal with it like any other .NET object.

提交回复
热议问题