Home > OS >  SimpleJSON how the get "location" item values in JSON array
SimpleJSON how the get "location" item values in JSON array

Time:01-25

"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;  

CodePudding user response:

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();
}

CodePudding user response:

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 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<Node[]>(jsonString);

and access

nodes[0].geometry.location.lat
  • Related