-1
"results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 50.4501,
               "lng" : 30.5234
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 50.59079800991073,
                  "lng" : 30.82594104187906
               },
               "southwest" : {
                  "lat" : 50.21327301525928,
                  "lng" : 30.23944009690609
               }
            }
         },

There are lat and lng values in geometry, but i can get only into "results" for now.

JSONNode root = JSONNode.Parse(www.downloadHandler.text);  
JSONArray nodes = root["results"].AsArray;  
derHugo
  • 83,094
  • 9
  • 75
  • 115

2 Answers2

0

Might be better to use JsonElement which is faster. I have tested this code against your json and it works.

public static double UsingJsonElement(string jsonString)
{
    var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonString);
    
    return jsonElement
        .GetProperty("geometry")
        .GetProperty("location").GetProperty("lat")
        .GetDouble();
    
    var viewportlat = jsonElement
        .GetProperty("geometry")
        .GetProperty("viewport").GetProperty("northeas").GetProperty("lat")
        .GetDouble();
}
Manik
  • 97
  • 1
  • 7
0

According to your JSON hierarchy I guess it would depend on exactly which set of lat/long you are interested in - there are three.

And then afaik you simply go down the hierarchy like e.g.

var firstNode = nodes[0];
var geometry = firstNode["geometry"];
var location = geometry["location"];
var lat = location["lat"].AsFloat;
var lng = location["lng"].AsFloat;

You might want to rather use Newtonsoft JSON.Net though and simply implement according target type

[Serializable]
public class Root
{
    public Node[] results;
}

[Serializable]
public class Node
{
    // again depending which values you are interested in
    // you only have to implement th hierarchy of values you care for 
    // the rest will be ignored
    public Geometry geometry;
}

[Serializable]
public class Geometry
{
    public Location location;
}

[Serializable]
public class Location
{
    public float lat;
    public float lng;
}

and then simply go

var nodes = JsonConvert.DeserializeObject<Root>(jsonString).results;

and access

var lat = nodes[0].geometry.location.lat;
var lng = nodes[0].geometry.location.lng;
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Kinda interesting, but it makes some mess in code cause of those new classes – IServeladik I Jan 27 '23 at 10:08
  • With that method i got |Null| in "nodes" – IServeladik I Jan 27 '23 at 10:28
  • @IServeladikI typed that on the phone ^^ Your json has one more root object with the property `results` so you need that one as well ... I don't see that as a mess .. it is way less a mess than having a bunch of magic strings ;) – derHugo Jan 27 '23 at 11:51