Home > Mobile >  Traverse a JsonNode
Traverse a JsonNode

Time:12-09

This is how much JsonNode response looks like. 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"
    }
}```

CodePudding user response:

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:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

class Test2 {
    public static void main(String[] args) {
        try (Reader reader = new FileReader("/tmp/test.json")) {
            JSONObject root = (JSONObject)(new JSONParser()).parse(reader);
            System.out.println("Message: "   root.get("message"));
            JSONObject results = (JSONObject) root.get("results");
            for (Object key: results.keySet())
                System.out.println(key   ": "   results.get(key));
        } catch (IOException | ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Result:

Message: Results field contain api response
Person 1: USA
Person 2: India
People: Germany
Name 3: Europe

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.

  • Related