Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON in Java

Tags:

java

json

I am currently working with Java, reading JSON response from a webservice. Till now I have been parsing JSON for a path known in advance. So I am able to make objects and arrays depending on situation.

String jsonText = readAll(br);
JSONObject json = new JSONObject(jsonText);
JSONObject resp = json.getJSONObject("Response");

But now I have a problem. I have to ask user to provide me a path and I have to get the value at that path in JSON response. Path could be incorrect - return error in that case.

Kind of like XPath in XML. Do we have something similar in JSON?

Path could for example look like: /Response/VehicleSearch/Vehicles/Vehicle[2]/Features/Feature[7]/ID

Please excuse me if its a stupid question. Any help is appreciated. Thanks in advance.

like image 277
Rahul Dabas Avatar asked Aug 24 '26 23:08

Rahul Dabas


1 Answers

For JSON equivalent of XPATH for XML you can use JsonPath

As per docs:

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is available in many programming languages such as Javascript, Python and PHP. Now also in Java!

like image 123
anubhava Avatar answered Aug 27 '26 13:08

anubhava