Ilkar
Ilkar

Reputation: 2177

Java JSONObject get children

i want to create gmaps on my website.

I found, how to get coordinates.

    {
   "results" : [
      {
         // body
         "formatted_address" : "Puławska, Piaseczno, Polska",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 52.0979041,
                  "lng" : 21.0293984
               },
               "southwest" : {
                  "lat" : 52.0749265,
                  "lng" : 21.0145743
               }
            },
            "location" : {
               "lat" : 52.0860667,
               "lng" : 21.0205308
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : 52.0979041,
                  "lng" : 21.0293984
               },
               "southwest" : {
                  "lat" : 52.0749265,
                  "lng" : 21.0145743
               }
            }
         },
         "partial_match" : true,
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}

I want to get:

 "location" : {
           "lat" : 52.0860667,
           "lng" : 21.0205308
        },

From this Json.

I decided to user json-simple

<dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>

My code is:

String coordinates = //JSON from google

JSONObject json = (JSONObject)new JSONParser().parse(coordinates);

And i can get the first children: "results"

String json2 = json.get("results").toString();

json2 display correct body of "results"

But i cannot get "location" children.

How to do it ?

Thanks

Upvotes: 6

Views: 32141

Answers (2)

Hossein Kurd
Hossein Kurd

Reputation: 4555

about this link

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

Upvotes: 0

Woodham
Woodham

Reputation: 4273

I think you need to cast the call to json.get("results") to a JSONArray.

I.e.

String coordinates = //JSON from google

JSONObject json = (JSONObject)new JSONParser().parse(coordinates);

JSONArray results = (JSONArray) json.get("results");

JSONObject resultObject = (JSONObject) results.get(0);

JSONObject location = (JSONObject) resultObject.get("location");

String lat = location.get("lat").toString();

String lng = location.get("lng").toString()

The trick is to look at what type the part of the json you're deserializing is and cast it to the appropriate type.

Upvotes: 13

Related Questions