Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a JSONObject subfield?

I feel dumb but I've been looking around for this for a while. I'm working with the google geocoder API and I need a bit of help with the json responses. Here is a JSONObject that I have:

{
"viewport": {
    "southwest": {
        "lng": -78.9233749802915,
        "lat": 36.00696951970851
    },
    "northeast": {
        "lng": -78.92067701970849,
        "lat": 36.0096674802915
    }
},
"location_type": "ROOFTOP",
"location": {
    "lng": -78.922026,
    "lat": 36.0083185
}
}

How do I pull the "location" subfields out into their own variables? I tried jsonObjectVariable.getString("location"); and jsonObjectVariable.getDouble() etc. but it's not returning correctly. What do you call a subfield in a json object? I've read that you can access subfields with the object.subobject syntax but I'm just not getting what I need.

(I'm using json-org as the library)

Thanks for the help!

like image 737
El Duderino Avatar asked Apr 17 '12 19:04

El Duderino


2 Answers

With the json.org library for Java, you can only get at the individual properties of an object by first getting the parent JSONObject instance:

JSONObject object = new JSONObject(json);
JSONObject location = object.getJSONObject("location");
double lng = location.getDouble("lng");
double lat = location.getDouble("lat");

If you're trying to access properties using "dotted notation", like this:

JSONObject object = new JSONObject(json);
double lng = object.getDouble("location.lng");
double lat = object.getDouble("location.lat");

then the json.org library isn't what you're looking for: It does not support this kind of access.


As a side node, it makes no sense calling getString("location") on any part of the JSON given in your question. The value of the only property that is called "location" is another object with two properties called "lng" and "lat".

If you want this "as a String", the closest thing is to call toString() on the JSONObject location (first code snippet in this answer) which will give you something like {"lng":-78.922026,"lat":36.0083185}.

like image 56
Philipp Reichart Avatar answered Sep 25 '22 02:09

Philipp Reichart


I believe you'd need to use jsonObjectVariable.getJSONObject("location") which in turn returns another JSONObject.

You can then invoke getDouble("lng") or getDouble("lat") on that object.

E.g.

double lat = jsonObjectVariable.getJSONObject("location").getDouble("lat");
like image 43
Bruce Lowe Avatar answered Sep 22 '22 02:09

Bruce Lowe