Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 843
Ilkar Avatar asked Jun 09 '14 08:06

Ilkar


1 Answers

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.

like image 163
Woodham Avatar answered Sep 19 '22 01:09

Woodham