How to Read Nested JSON Data In Java

  • Post last modified:December 15, 2022
  • Reading time:3 mins read

Introduction

  • JSON is a very common data type for data exchange over the internet. When we read JSON data in our favorite programming language we often read the tree structure and map it to some data type.
  • In this article, we will use Jackson object mapper library to read nested JSON data

Input Data

  • Our input data contains nested JSON objects for quizzes. it contains a quiz type and all the questions for that type with options and answers.
{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

Library

 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.0-rc1</version>
        </dependency>

ObjectMapper

  • Jackson library provides ObjectMapper instance that provides many methods that takes input as JSON string /url of the file etc and return JsonNode object.
  • JsonNode object allows us to read JSON as readTree and we can iterate over it and read the attributes we need.

Logic

  • In our code, we use the JsonNode object and get the quiz attribute from Json Data.
  • Now we know that the QuizNode contains multiple records for each quiz type so we can iterate over it and for each type we can extract question and options.
URL jsonFile = JSONToJava.class.getClassLoader().getResource("example_2.json");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonFile);
        JsonNode quiz = jsonNode.get("quiz");

        quiz.forEach(q-> {
            q.forEach(a-> {
                System.out.println("question: "+a.get("question"));
                System.out.println("options: "+a.get("options"));
            });
        });
  • We can also use fields() method over JsonNode for quiz attributes. This method will return all the quiz types as keys and values would be question attributes.
URL jsonFile = JSONToJava.class.getClassLoader().getResource("example_2.json");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonFile);
        JsonNode quiz = jsonNode.get("quiz");

        Iterator<Map.Entry<String, JsonNode>> fields = quiz.fields();
        while (fields.hasNext()){
            Map.Entry<String, JsonNode> next = fields.next();
            System.out.println(next.getKey());
            next.getValue().forEach(a-> System.out.println(a));
        }

Conclusion

  • In this article, we used Jackson ObjectMapper to read Json data in Java.
    ObjectMapper provides many methods to read the Json data as a tree and iterate over each JSON object by name or position. It’s a simple and quick way to read Json data in Java.

Bonus Tip

Leave a Reply