Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access nested json data in single get?

Tags:

java

json

I am trying to trying to get a value out of a json object. How would I get a third level json object:

json format looks like:

feedString = {"level1":[{"level2":{"level3":{"valueIWant":10}}}]}

Code is:

JSONObject  jsonFeed = new JSONObject(feedString);
jsonFeed.get("level1.level2.level3.valueIWant");

Can I get nested levels in one get? What should my key look like?

like image 599
Lumpy Avatar asked Nov 13 '11 01:11

Lumpy


People also ask

How do I access a nested object in JSON?

Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.

How can I access specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

Can you have newlines in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.


3 Answers

You could give JSONiJ (JSON in Java) a shot; it's a Java version of JSONPath and basically maps (a subset of) XPath syntax onto JSON objects.

Also, see this SO question for some other ideas; it looks like json-path has a Java version, and uses dot notation.

The other option is to build an EL bridge between JSONObjects and something like MVEL or OGNL, which would give you the more-familiar dot notation. (I thought there was an MVEL/JSON bridge, but can't find it now.)

like image 179
Dave Newton Avatar answered Oct 16 '22 02:10

Dave Newton


You should use JSONPath. Check out this Java implementation http://code.google.com/p/json-path/

like image 34
kalle Avatar answered Oct 16 '22 02:10

kalle


It's been a while now, but I have some good news. Just tried beanutils and it works like a charm! Assuming you have the json converted to map: (any parser can do that)

private Map<String, Object> json;

All you need is:

PropertyUtils.getProperty(json, "level1.level2.level3.valueIWant")

Have fun :)

like image 20
avim Avatar answered Oct 16 '22 03:10

avim