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.
-
try using GSON , a google library for dealing with JSONSatya– Satya2013年08月30日 18:01:17 +00:00Commented Aug 30, 2013 at 18:01
-
1For a solution with Gson, see here: stackoverflow.com/questions/15658124/…Sotirios Delimanolis– Sotirios Delimanolis2013年08月30日 18:10:20 +00:00Commented Aug 30, 2013 at 18:10
-
You have the JSON decomposed into a tree structure. You access that with a "path" just as you'd access the XML, though you may have to step through the branches yourself vs using a path notation.Hot Licks– Hot Licks2013年08月30日 19:04:16 +00:00Commented Aug 30, 2013 at 19:04
-
1(This is not a "stupid" question, but you've obviously not put much effort into research.)Hot Licks– Hot Licks2013年08月30日 19:04:58 +00:00Commented Aug 30, 2013 at 19:04
-
I did look up and found json-path. I am currently playing with it and having some problem for which I posted another question. I am kind of on a short leash with this one hence posted the question right off.Rahul Dabas– Rahul Dabas2013年08月30日 19:09:22 +00:00Commented Aug 30, 2013 at 19:09
1 Answer 1
For JSON equivalent of XPATH for XML you can use JsonPath
As per docs:
JsonPathis toJSONwhatXPATHis toXML, a simple way to extract parts of a given document.JsonPathis available in many programming languages such asJavascript,PythonandPHP. Now also in Java!