Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing complex object using Json.NET

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

{
    "destination_addresses": [
        "Via Medaglie D'Oro, 10, 47121 Forlì FC, Italia",
        "Via Torino, 20123 Milano, Italia",
        "Via Guglielmo Marconi, 71, 40121 Bologna, Italia",
        "Via Irnerio, 40126 Bologna, Italia"
    ],
    "origin_addresses": [
        "Via Medaglie D'Oro, 10, 47121 Forlì FC, Italia",
        "Via Torino, 20123 Milano, Italia",
        "Via Guglielmo Marconi, 71, 40121 Bologna, Italia",
        "Via Irnerio, 40126 Bologna, Italia"
    ],
    "rows": [
        {
            "elements": [
                {
                    "distance": {
                        "text": "1 m",
                        "value": 0
                    },
                    "duration": {
                        "text": "1 min",
                        "value": 0
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "286 km",
                        "value": 286281
                    },
                    "duration": {
                        "text": "2 ore 48 min",
                        "value": 10083
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "80,1 km",
                        "value": 80088
                    },
                    "duration": {
                        "text": "1 ora 3 min",
                        "value": 3789
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "77,6 km",
                        "value": 77594
                    },
                    "duration": {
                        "text": "57 min",
                        "value": 3422
                    },
                    "status": "OK"
                }
            ]
        },
        {
            "elements": [
                {
                    "distance": {
                        "text": "288 km",
                        "value": 287811
                    },
                    "duration": {
                        "text": "2 ore 48 min",
                        "value": 10052
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "1 m",
                        "value": 0
                    },
                    "duration": {
                        "text": "1 min",
                        "value": 0
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "212 km",
                        "value": 212423
                    },
                    "duration": {
                        "text": "2 ore 8 min",
                        "value": 7664
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "218 km",
                        "value": 218219
                    },
                    "duration": {
                        "text": "2 ore 9 min",
                        "value": 7740
                    },
                    "status": "OK"
                }
            ]
        },
        {
            "elements": [
                {
                    "distance": {
                        "text": "78,5 km",
                        "value": 78528
                    },
                    "duration": {
                        "text": "56 min",
                        "value": 3346
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "212 km",
                        "value": 212190
                    },
                    "duration": {
                        "text": "2 ore 5 min",
                        "value": 7519
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "1 m",
                        "value": 0
                    },
                    "duration": {
                        "text": "1 min",
                        "value": 0
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "2,0 km",
                        "value": 1979
                    },
                    "duration": {
                        "text": "5 min",
                        "value": 316
                    },
                    "status": "OK"
                }
            ]
        },
        {
            "elements": [
                {
                    "distance": {
                        "text": "74,7 km",
                        "value": 74719
                    },
                    "duration": {
                        "text": "55 min",
                        "value": 3278
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "218 km",
                        "value": 217951
                    },
                    "duration": {
                        "text": "2 ore 9 min",
                        "value": 7712
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "3,8 km",
                        "value": 3782
                    },
                    "duration": {
                        "text": "11 min",
                        "value": 671
                    },
                    "status": "OK"
                },
                {
                    "distance": {
                        "text": "1 m",
                        "value": 0
                    },
                    "duration": {
                        "text": "1 min",
                        "value": 0
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "status": "OK"
}

I need to create a Distance Matrix so I'm only interested in the "value" field inside "distance".

I've tried this approach:

DataSet data = JsonConvert.DeserializeObject<DataSet>(jsonResponse);
        DataTable dataTab = data.Tables["Elements"];
        foreach (DataRow elements in dataTab.Rows)
        {
            Console.WriteLine(elements["distance"]);
            //Do something else here
        }

But The JSonConvert returns "Additional text found in JSON string after finishing deserializing object."

like image 689
Federico Avatar asked Dec 13 '13 14:12

Federico


People also ask

How do you deserialize complex JSON?

Json to Deserialize a Complex Json. When we are using a framework version earlier than . NET 3.0, it is recommended to use Newtonsoft. Json to serialize and deserialize objects.

How do I deserialize a JSON object in Web API?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is Deserializing a JSON?

The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON.

What is serializing and deserializing JSON in C#?

Json structure is made up with {}, [], comma, colon and double quotation marks and it includes the following data types: Object, Number, Boolean, String, and Array. Serialize means convert an object instance to an XML document. Deserialize means convert an XML document into an object instance.


3 Answers

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; }
}
like image 96
Tim S. Avatar answered Oct 27 '22 04:10

Tim S.


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);
    }
  }
like image 25
Kyle B. Avatar answered Oct 27 '22 05:10

Kyle B.


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;
    }
}
like image 1
Julien Roncaglia Avatar answered Oct 27 '22 04:10

Julien Roncaglia