Query a JSONObject in java

Pamput picture Pamput · Mar 15, 2013 · Viewed 56.6k times · Source

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:

String json = "{ data: { data2 : { value : 'hello'}}}";

...
// Somehow we managed to convert json to jsonObject
...

String result = jsonObject.getAsString("data.data2.value");

System.out.println(result);

I expect to get "hello" as output.

So far, the fastest way I have found is using Gson:

jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();

It's not actually easy to write and read. Is there something faster?

Answer

n1ckolas picture n1ckolas · Mar 21, 2013

I've just unexpectedly found very interesting project: JSON Path

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.

With this library you can do what you are requesting even easier, then my previous suggestion:

String hello = JsonPath.read(json, "$.data.data2.value");

System.out.println(hello); //prints hello

Hope this might be helpful either.