-1

I want to parse below JSON in ASP.NET.

{
    "destination_addresses": [
        "Address 1"
    ],
    "origin_addresses": [
        "Address 2"
    ],
    "rows": [
        {
            "elements": [
                {
                    "distance": {
                        "text": "15.7 km",
                        "value": 15664
                    },
                    "duration": {
                        "text": "17 mins",
                        "value": 1036
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "status": "OK"
}

I want to retrieve the text and value from a distance token. I was able to reach till elements.

var objectjson = JObject.Parse(response.Content);
dynamic dynJson = JsonConvert.DeserializeObject(objectjson["rows"].ToString());
var elements = dynJson[0].ToString();
var firstElement = JObject.Parse(elements);

How to parse the json further to reach to the distance token and then text and value?

Adi
  • 405
  • 1
  • 7
  • 13
  • 2
    Create class objects that represent that data and then deserialize the json... It could be as simple as `Root myClass = JsonConvert.DeserializeObject(response.Content);` – Trevor Nov 21 '20 at 20:33

4 Answers4

1

Create a class like:

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 Root    {
    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; } 
}

then, you can convert on it and construct your logic easylly

var myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

Sites references:

Json2Csharp NewtonSoft

Fabio
  • 30
  • 5
1

If you don't want to design a data model corresponding to your JSON, you can access nested JToken values using its item indexer:

var distance = objectjson["rows"]?[0]?["elements"]?[0]?["distance"];

var text = (string)distance?["text"];
var value = (decimal?)distance?["value"]; // Or int or double, if you prefer.

You can also use SelectToken() to access nested values:

var distance = objectjson.SelectToken("rows[0].elements[0].distance");

Notes:

  • There is no need to reformat and reparse the JSON simply to access nested data. I.e. JsonConvert.DeserializeObject(objectjson["rows"].ToString()) is superfluous and will harm performance.

  • I am using the null-conditional operator ?[] to access nested tokens in case any of the intermediate properties are missing. If you are sure the properties are never missing or would prefer to throw an exception, you can do

    var distance = objectjson["rows"][0]["elements"][0]["distance"];
    

Demo fiddle here.

dbc
  • 104,963
  • 20
  • 228
  • 340
1

You can traverse the data this way:

    ' strBuf = your json string

    Dim jOb As JObject = JObject.Parse(strBuf)
    Dim MyDistance As JToken = jOb.SelectToken("rows[0].elements[0]")

After above, then

    Text   = MyDistance.SelectToken("distance.text").ToString
    value  = MyDistance.SelectToken("distance.value").ToString
    Status = MyDistance.SelectToken("status").ToString

The above will get you the 3 values. Note that each of the rows are repeating data, so it not clear if you have one string, and with to pull the values, or pull multiple values? If you need to pull repeating data, then above would change.

The above is vb, but it quite much the same in c#.

Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
1

Take this sample json and:

  1. Go to visual studio
  2. In the menu -> Edit -> Paste Special -> Paste JSON and Classes

VS will generate the classes for you. It will generate the root type as Root, rename it to whatever you want or leave it as Root. Then you can simply deserialise your string into that class.

var rootObject = JsonConvert.DeserializeObject<Root>(response.Content);

// Simply use rootObject to access any property
var firstElement = rootObject.rows[0].elements[0];

// firstElement.distance.text 
// firstElement.distance.value
// firstElement.duration.text
// firstElement.duration.value
// firstElement.status
CoOl
  • 2,637
  • 21
  • 24
  • This was very helpful to me for this JSON and as well as for other web services responses. Thank you. – Adi Nov 25 '20 at 20:15
  • Glad it helped, please feel free to mark it as the answer if you think it was useful. – CoOl Nov 26 '20 at 07:52