CodeGym /Courses /JAVA 25 SELF /Working with dynamic structures: Map, List, JsonNode

Working with dynamic structures: Map, List, JsonNode

JAVA 25 SELF
Level 46, Lesson 3
Available

1. Reading JSON into Map and List

Usually, when we work with JSON, we know its structure in advance and can describe it as a Java class. In practice, though, things aren’t that predictable: fields may appear and disappear, and nesting may change. In such cases, it’s much more convenient to operate with universal data structures — Map, List — or JSON trees.

Creating a Java model for every variation is time-consuming and brittle. Universal collections and trees let you flexibly extract only the needed parts without tying yourself to a fixed schema.

Deserializing a JSON object into Map

JSON example:

{
  "id": 123,
  "name": "Alice",
  "email": "alice@example.com",
  "active": true
}

Deserialization into Map:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"id\":123,\"name\":\"Alice\",\"email\":\"alice@example.com\",\"active\":true}";

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> data = mapper.readValue(json, Map.class);

        System.out.println(data);
        // Output: {id=123, name=Alice, email=alice@example.com, active=true}
    }
}

Now you can access any field as a map entry:

System.out.println(data.get("name")); // Alice

Deserializing an array of objects into List

JSON array:

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

Deserialization:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;

public class UsersReadExample {
    public static void main(String[] args) throws Exception {
        String json = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]";

        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> users = mapper.readValue(json, List.class);

        for (Map<String, Object> user : users) {
            System.out.println(user.get("name"));
        }
        // Output:
        // Alice
        // Bob
    }
}

Important note: when reading into universal structures, all nested objects become Map, and arrays become List. For complex structures, you’ll have to cast carefully and check types:

Object items = data.get("items");
if (items instanceof List) {
    List<?> itemList = (List<?>) items;
    // ...
}

2. JsonNode: JSON tree in Jackson

Working with Map/List is convenient but unsafe: you can make a type mistake or miss nesting. Jackson offers a more powerful tool — the JsonNode class. It’s a universal tree where each node is an object, array, value, or null.

Getting JsonNode

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class JsonNodeStart {
    public static void main(String[] args) throws Exception {
        String json = "{\"id\":123,\"name\":\"Alice\",\"tags\":[\"java\",\"json\"]}";
        ObjectMapper mapper = new ObjectMapper();

        JsonNode root = mapper.readTree(json);
        // root is the root of the JSON tree
    }
}

Accessing fields

int id = root.get("id").asInt();         // 123
String name = root.get("name").asText();  // Alice
JsonNode tags = root.get("tags");         // array

System.out.println("Name: " + name);

Iterating an array

for (JsonNode tag : tags) {
    System.out.println(tag.asText());
}
// Output:
// java
// json

Nested objects

Example of a complex JSON:

{
  "user": {
    "id": 1,
    "profile": {
      "nickname": "java_guru",
      "age": 25
    }
  }
}

Extracting a nested value:

JsonNode profile = root.get("user").get("profile");
String nickname = profile.get("nickname").asText();
System.out.println(nickname); // java_guru

Safe access: get vs path

- get("key") — if the key is absent, returns null. Any call like asText() on null will cause a NullPointerException.
- path("key") — if the key is absent, returns an “empty” node, and asText() yields "", asInt() — 0.

String phone = root.path("phone").asText(); // "" if the field is missing

Checking node type

if (root.has("tags") && root.get("tags").isArray()) {
    for (JsonNode tag : root.get("tags")) {
        // ...
    }
}

Modifying JsonNode

JsonNode is immutable. To create/modify a tree, use ObjectNode/ArrayNode.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

ObjectMapper mapper = new ObjectMapper();

// Creating a new object
ObjectNode obj = mapper.createObjectNode();
obj.put("id", 10);
obj.put("name", "Bob");

// Adding an array
ArrayNode arr = mapper.createArrayNode();
arr.add("Java").add("JSON");
obj.set("tags", arr);

System.out.println(obj.toPrettyString());
/*
{
  "id" : 10,
  "name" : "Bob",
  "tags" : [ "Java", "JSON" ]
}
*/

3. Working with Gson: JsonElement, JsonObject, JsonArray

Jackson isn’t the only player. Gson also provides a convenient API for dynamic JSON: JsonElement, JsonObject, JsonArray.

Parsing into JsonElement

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

String json = "{\"id\":123,\"name\":\"Alice\",\"tags\":[\"java\",\"json\"]}";
JsonElement root = JsonParser.parseString(json);

Accessing fields

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

JsonObject obj = root.getAsJsonObject();
int id = obj.get("id").getAsInt();
String name = obj.get("name").getAsString();
JsonArray tags = obj.getAsJsonArray("tags");

for (JsonElement tag : tags) {
    System.out.println(tag.getAsString());
}

Nesting and safety

if (obj.has("email")) {
    String email = obj.get("email").getAsString();
}

Working with arrays

String arrJson = "[{\"id\":1},{\"id\":2}]";
JsonArray arr = JsonParser.parseString(arrJson).getAsJsonArray();

for (JsonElement el : arr) {
    JsonObject item = el.getAsJsonObject();
    System.out.println(item.get("id").getAsInt());
}

Modification

In Gson, objects are mutable — you can add and remove fields:

import com.google.gson.JsonObject;

JsonObject newObj = new JsonObject();
newObj.addProperty("id", 42);
newObj.add("tags", tags);
System.out.println(newObj.toString());

4. Practice: extracting data from an unknown JSON

Task: Suppose we have a JSON config whose structure can change:

{
  "service": "mail",
  "enabled": true,
  "params": {
    "host": "smtp.example.com",
    "port": 587
  }
}

Extract host and port using Jackson:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
JsonNode params = root.path("params");
String host = params.path("host").asText();
int port = params.path("port").asInt();

System.out.println(host + ":" + port); // smtp.example.com:587

The same with Gson:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

JsonObject rootObj = JsonParser.parseString(json).getAsJsonObject();
JsonObject params = rootObj.getAsJsonObject("params");
String host = params.get("host").getAsString();
int port = params.get("port").getAsInt();

System.out.println(host + ":" + port);

5. Common mistakes and nuances

Error #1: Incorrect type casting. If you expect a string but the field holds a number or null, calling asText() or getAsString() may yield an unexpected result or an exception. For example, if the field is missing, root.get("foo").asText() will lead to a NullPointerException.

Error #2: Missing null checks. Especially with nested access: root.get("params").get("host"). If params is absent, you’ll get an NPE. In Jackson, use path(); in Gson, check presence via has and type via isJsonObject()/isJsonArray().

Error #3: Confusing node types. If a field is an array and you treat it as an object, you’ll get an error. Check types: Jackson — isArray()/isObject(), Gson — isJsonArray()/isJsonObject().

Error #4: Loss of type information when working with Map/List. When deserializing into Map<String, Object>, nested structures become a cascade of Map/List, which complicates navigation and leads to numerous casts and instanceof checks.

Error #5: Misunderstanding mutability. In Jackson, JsonNode is immutable, and you must modify via ObjectNode and ArrayNode. In Gson, objects are mutable; remember that changing a node affects all references to it in the current tree.

1
Task
JAVA 25 SELF, level 46, lesson 3
Locked
Extracting data from a game profile 🎮
Extracting data from a game profile 🎮
1
Task
JAVA 25 SELF, level 46, lesson 3
Locked
Processing a list of cities for the travel guide 🗺️
Processing a list of cities for the travel guide 🗺️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION