-2

What is the most efficient apprach to read such JSON file. To be honest what i need to take from that JSON is the distance. Inside elements node there could be either one or multiple items containing distance and duration. I need to SUM all of that values from each element's node: distance-text. For example: 324 km (distance in kilemeters). I shown below 3 examples. How can i do that?

Morover in last example if request is bad there could be something like "NOT_FOUND" (or something else besides "OK"). If in any "status" there would be something diffrent than "OK" at east in one i should get throw Exception().

JSON response example 1:

{
   "destination_addresses" : [ "Długa 50, 05-075 Warszawa, Slovakia" ],
   "origin_addresses" : [ "Wilenska 2, Zabrze, Slovakia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "324 km",
                  "value" : 323619
               },
               "duration" : {
                  "text" : "3 hours 16 mins",
                  "value" : 11776
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

In this case i should calculate as: 324

JSON response example 2: (There could be more elements like here)

{
   "destination_addresses" : [ "Długa 50, 05-075 Warszawa, Slovakia" ],
   "origin_addresses" : [ "Wilenska 2, Zabrze, Slovakia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "324 km",
                  "value" : 323619
               },
               "duration" : {
                  "text" : "3 hours 16 mins",
                  "value" : 11776
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "192 km",
                  "value" : 191950
               },
               "duration" : {
                  "text" : "2 hours 26 mins",
                  "value" : 8732
               },
               "status" : "OK"
            },
         ]
      }
   ],
   "status" : "OK"
}

In this case i should calculate as: 516

JSON response example 3: (with some statuses diffrent than "OK")

{
   "destination_addresses" : [ "", "", "" ],
   "origin_addresses" : [ "" ],
   "rows" : [
      {
         "elements" : [
            {
               "status" : "NOT_FOUND"
            },
            {
               "status" : "OK"
            },
            {
               "status" : "NOT_FOUND"
            }
         ]
      }
   ],
   "status" : "ERR" 
}

In this case i should get Exception

4
  • 1
    Q: I'm curious: why "Slovakia", and not "Poland"? To answer your question: you DON'T want to "check for a string". You want to add Json.Net (a NuGet package) to your project, and call JsonConvert.Deserialize(): hanselman.com/blog/… Commented Sep 6, 2020 at 20:41
  • @paulsm4 I have some generator for other purposes but it's not the case for that topic. Commented Sep 6, 2020 at 21:08
  • 1
    Use NewtonSoft library. You can call JsonConvert.DeserializeObject(). It would create an object of your JSON that you can loop through a foreach. Then just add up each "distance" from this object to a new variable if the status is "OK", otherwise throw an Exception. Commented Sep 6, 2020 at 21:11
  • @ThomasH can you post the answer? Don;t know how to get those values (still trying) Commented Sep 6, 2020 at 23:05

1 Answer 1

2

you can use https://json2csharp.com/ to generate C# classes based on your json structure.

then install nuget package https://www.nuget.org/packages/Json.Net/

then you can try the following code:

var sampleJson = @"{


""destination_addresses"" : [ ""Długa 50, 05-075 Warszawa, Slovakia"" ],
   ""origin_addresses"" : [ ""Wilenska 2, Zabrze, Slovakia"" ],
   ""rows"" : [
      {
         ""elements"" : [
            {
               ""distance"" : {
                  ""text"" : ""324 km"",
                  ""value"" : 323619
               },
               ""duration"" : {
                  ""text"" : ""3 hours 16 mins"",
                  ""value"" : 11776
               },
               ""status"" : ""OK""
            },
            {
               ""distance"" : {
                  ""text"" : ""192 km"",
                  ""value"" : 191950
               },
               ""duration"" : {
                  ""text"" : ""2 hours 26 mins"",
                  ""value"" : 8732
               },
               ""status"" : ""OK""
            },
         ]
      }
   ],
   ""status"" : ""OK""
}";

    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(sampleJson);
    if (obj.status != "OK")
    {
        throw new Exception($"Status is: {obj.status}");
    }

    if (obj.rows.Any(r => r.elements.Any(e => e.status != "OK")))
    {
        throw new Exception("some of the elements status is not ok");
    }

    var allDistanceText = obj.rows?.Select(e => e.elements).SelectMany(e => e.Select(d => d.distance?.text));
    int sum = allDistanceText.Select(dt => dt?.Replace("km", "")?.Trim())
        .Sum(dt =>
        {
            if (int.TryParse(dt, out int results))
            {
                return results;
            }
            return 0;
        });
    sum.Dump();
Sign up to request clarification or add additional context in comments.

3 Comments

I get null on var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonstring); I provided from my examples.
Which json sample are you trying?
all is good, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.