I have a below JSON Array from the below, I want to get commandResponse associated with searched Command.
e.g. lets say I searched command "show version", It should return my commandResponse as 16.0.1.
JSON Array
[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]
Note: If you see JSON data show version word is present 2 times, show version & show version log but it should return only show version command data.
I tried to do this using JsonPath:
List<Map<String, Object>> finalDataList = commandsData.read("$[?(@.command == 'Show Version')]");
But it gives me below error:
The method parse(String) is undefined for the type JsonPath
Notes:
-
JSON parser Library – com.googlecode.json-simple
-
commandsData – This is JSON Array
3
Answers
For me, it was easier to map JSONArray to Map<String,Object> and implement functionality there!
Below is attached my code on kotlin
The output is
Added java code
You may consider another library Josson to do the job.
https://github.com/octomix/josson
Output
To find the required JSON-object in the array, you need to iterate over array elements and check if it contains the target value (like
"Show Version"
). If the matching object was found, you need to extract the value that corresponds to"commandResponse"
from it.Here’s how it might be implemented using Stream API (
JSONArray
is a subtype ofArrayList
therefore we can invokestream()
on it):Usage example:
Output:
Note: I would not recommend using
org.json.simple
for any task apart from very trivial. It is very unflexible, and not type-safe. ItsJSONArray
extendsArrayList
of row type, for that reason type casts pop up all over the place.