简体   繁体   中英

How to iterate a big Json in Java that can have multiple level of Objects and Arrays without using a pojo class?

How to iterate a big Json in Java that can have multiple levels of Objects and Arrays without using a pojo class for parsing? The objects and Array key names are unknown. Is there any common code that can do this? In this sample json all the data in value key has to be printed. Sample Json:

"X": [
        {
            "Y": {
                "value": "Test"
            },
            "Z": {
                "value": 2
            }
}
]

The real json can be really big with multiple Array and object levels.

NB: Please don't mark this as duplicate as other questions are not about the exact requirement.

Using Jackson, you can read\load the JSON as follows:

private JsonNode loadJson(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readTree(json);
    return rootNode;
}

Sample JSON :

{
  "name":{
    "first":"Tatu",
    "last":"Saloranta"
  },
  "title":"Jackson founder",
  "company":"FasterXML",
  "pets":[
    {
      "type":"dog",
      "number":1
    },
    {
      "type":"fish",
      "number":50
    }
  ]
}

To parse the JSON :

String json = "{\"name\": {\"first\":\"Tatu\",\"last\":\"Saloranta\"},\"title\":\"Jackson founder\",\"company\":\"FasterXML\",\"pets\":[{\"type\":\"dog\",\"number\":1},{\"type\":\"fish\",\"number\":50}]}";

JsonNode rootNode = loadJson(json);

JsonNode nameNode = rootNode.get("name");
String firstName = nameNode.get("first").asText();
String lastName = nameNode.get("last").asText();

String title = rootNode.get("title").asText();
String company = rootNode.get("company").asText();

JsonNode petsArrayNode = rootNode.get("pets");
for (final JsonNode petNode : petsArrayNode ) {
  String type = petNode.get("type").asText();
  int number = petNode.get("number").asInt();
}

You can read more here: https://www.baeldung.com/jackson-json-node-tree-model

You can read JSON as a stream with JsonParser from JSR 374 (JSON Processing API aka JSON-P):

import java.io.*;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

public static class ParserTest {
    public static void main(String[] args) {
        String jsonString = "{\"X\": [\n" +
                "        {\n" +
                "            \"Y\": {\n" +
                "                \"value\": \"Test\"\n" +
                "            },\n" +
                "            \"Z\": {\n" +
                "                \"value\": 2\n" +
                "            }\n" +
                "}\n" +
                "]}";
        JsonParser parser = Json.createParser(new StringReader(jsonString));
        String key = null;

        while (parser.hasNext()) {
            Event event = parser.next();

            switch (event) {
                case KEY_NAME:
                    key = parser.getString();
                    break;
                case VALUE_STRING:
                case VALUE_NUMBER:
                case VALUE_TRUE:
                case VALUE_FALSE:
                case VALUE_NULL:
                    System.out.println(key + ": " + parser.getString());
                    break;
            }
        }
    }
}

You need to include glassfish implementation

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

Code sample taken from https://www.tutorialspoint.com/how-to-parse-a-json-string-using-streaming-api-in-java

You can read more about JSON-P here: https://javaee.github.io/jsonp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM