This is how much JsonNode response has different key value pairs, similar to the example below. How can I traverse it to get the response in both key and value pair. Thank you.
{
"message": "Results field contain api response",
"results": {
"Person 1": "USA",
"Person 2": "India",
"Name 3": "Europe",
"People": "Germany"
}
}```
2
Answers
This worked for me. PersonInfo class will contain getter and setter for person and country.
If you can assume the basic structure, where the top level is a map (JSONObject) that contains a ‘message’ key with a simple value, and a ‘results’ key with a value that is a collection of key/value pairs, then here’s how to read the structure with
JSON.simple
:Result:
If you can’t assume a specific structure, then you’d need to read the root and test its type. Then, if it’s a JSONObject, iterate over the keys and values in that object. You’d then have to test the type of each value in the iteration to know what to do with that value. You would keep going as deep as necessary to parse and process all the values in the structure. If you need to allow for JSONArray values, you’d to the same thing with those, iterating over the values in the array, repeating the process on each value. And so on and so on. A recursive function works great here, where when you find a new JSONObject or JSONArray value, you call the same function you’re in to process that sub-object.