Parse the JSON Response in C#

后端 未结 2 1504
爱一瞬间的悲伤
爱一瞬间的悲伤 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:25

    You could parse the JSON into concrete classes and work with those hereafter.

    To do so, you could use a service like json2csharp which generates classes based on the JSON you provided. Alternatively, you could use the Visual Studio built-in feature Paste JSON As Classes:

    public class Alternative
    {
        public double confidence { get; set; }
        public string transcript { get; set; }
    }
    
    public class Result
    {
        public List<Alternative> alternatives { get; set; }
        public bool final { get; set; }
    }
    
    public class RootObject
    {
        public List<Result> results { get; set; }
        public int result_index { get; set; }
    }
    

    You can then use JSON.NET to parse the stringified JSON to concrete class instances:

    var root = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
    
    0 讨论(0)
  • 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<MyRootObject>(responseFromServer);
    

    And deal with it like any other .NET object.

    0 讨论(0)
提交回复
热议问题