Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a JSONObject in java

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?

like image 901
Pamput Avatar asked Mar 15 '13 10:03

Pamput


People also ask

How do I query a JSON object?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

How do you parse a JSON object in Java?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

What is JSON object in Java?

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.


1 Answers

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.

like image 170
n1ckolas Avatar answered Sep 25 '22 09:09

n1ckolas