Deserializing complex object using Json.NET

前端 未结 3 1396
甜味超标
甜味超标 2021-01-02 04:19

I need to deserialize the this json returned from grogle maps api:

{
    \"destination_addresses\": [
        \"Via Medaglie D\'Oro, 10, 47121 Forlì FC, Ital         


        
相关标签:
3条回答
  • 2021-01-02 04:20

    Using dynamic :

    dynamic json = JsonConvert.DeserializeObject(jsonResponse);
    
    var rowCount = json.rows.Count;
    Func<dynamic, int> getElementCount = r => r.elements.Count;
    var maxElements = Enumerable.Max(json.rows, getElementCount);
    
    var matrix = new int?[rowCount, maxElements];
    for(int i = 0; i < rowCount; i++)
    {
        var elements = json.rows[i].elements;
        for(int j = 0; j < elements.Count; j++)
        {
            var element = elements[j];
            matrix[i, j] = element.distance.value;
        }
    }
    
    0 讨论(0)
  • 2021-01-02 04:34

    You should deserialize to classes that match your data. You can generate these classes at http://json2csharp.com/.

    // use like
    var rootObj = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
    foreach (var row in rootObj.rows)
    {
        foreach (var element in row.elements)
        {
            Console.WriteLine(element.distance.text);
        }
    }
    
    // you might want to change the property names to .Net conventions
    // use [JsonProperty] to let the serializer know the JSON names where needed
    public class Distance
    {
        public string text { get; set; }
        public int value { get; set; }
    }
    
    public class Duration
    {
        public string text { get; set; }
        public int value { get; set; }
    }
    
    public class Element
    {
        public Distance distance { get; set; }
        public Duration duration { get; set; }
        public string status { get; set; }
    }
    
    public class Row
    {
        public List<Element> elements { get; set; }
    }
    
    public class RootObject
    {
        public List<string> destination_addresses { get; set; }
        public List<string> origin_addresses { get; set; }
        public List<Row> rows { get; set; }
        public string status { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-02 04:36

    I believe the issue is with the cast to 'DataSet' based on a similar question I found searching Stack Overflow.

    Try this as I believe it would work (you may need to use 'rows' instead of 'Elements', but I believe the approach of using a JObject will resolve the primary issue of the 'additional text'.

     JObject json = JsonConvert.DeserializeObject<JObject>(jsonResponse);
     foreach (Dictionary<string, object> item in data["Elements"])
     {
        foreach (string val in item.Values) {
            Console.WriteLine(val);
        }
      }
    
    0 讨论(0)
提交回复
热议问题