Mastering Jackson JsonNode in Spring Boot 3: From Parsing to Modification
This tutorial demonstrates how to use Jackson's JsonNode within a Spring Boot 3 environment to parse dynamic JSON, access and modify fields, convert nodes to POJOs, traverse the tree, and perform path‑based queries, providing complete code examples for each operation.
1. Introduction
When JSON structures are dynamic or unknown at compile time, traditional POJOs cannot be defined ahead of time. Using Map<String, Object> loses type information and makes nested access cumbersome. Jackson's JsonNode tree model preserves the full JSON hierarchy, allows type‑safe traversal, and enables selective deserialization of sub‑trees.
2. Sample JSON and POJOs
Example JSON representing a user with contact information and a list of orders:
static String json = """
{
"user": {
"name": "pack_xg",
"age": 33,
"contact": {
"email": "[email protected]",
"phones": ["13800138000", "010-12345678"]
}
},
"orders": [
{
"orderId": "D20260101001",
"items": [
{"name": "无线蓝牙耳机", "price": 299.99, "quantity": 1},
{"name": "手机保护壳", "price": 39.5, "quantity": 2}
],
"totalAmount": 379.0,
"shipped": true
}
]
}
""";Corresponding Java classes:
public class User {
private String name;
private int age;
private Contact contact;
private List<Order> orders;
}
public class Contact {
private String email;
private List<String> phones;
}
public class Order {
private String orderId;
private List<Item> items;
private double totalAmount;
private boolean shipped;
}
public class Item {
private String name;
private double price;
private int quantity;
}3. Basic JsonNode Operations
3.1 Parse JSON to an ObjectNode
ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.readValue(json, ObjectNode.class);3.2 Access fields
JsonNode userNode = rootNode.get("user");
System.out.println(userNode); // {"name":"pack_xg","age":33,"contact":{...}}
String name = userNode.get("name").asText();
int age = userNode.get("age").asInt();
System.out.println(name); // pack_xg
System.out.println(age); // 33
JsonNode phones = userNode.get("contact").get("phones");
if (phones.isArray()) {
phones.forEach(p -> System.out.println(p.asText()));
}
// 13800138000
// 010-123456783.3 Convert a JsonNode to a POJO
User user = mapper.treeToValue(userNode, User.class);
System.out.println(user);
// User[name=pack_xg, age=33, contact=Contact[[email protected], phones=[13800138000, 010-12345678]], orders=...]3.4 Find values
JsonNode emailNode = userNode.findValue("email");
System.out.println(emailNode.asText()); // [email protected]
JsonNode missing = userNode.findPath("nonexistent");
System.out.println(missing instanceof MissingNode); // true3.5 Iterate all properties of a node
userNode.fields().forEachRemaining(entry -> {
System.out.printf("%s : %s%n", entry.getKey(), entry.getValue());
});
// name : "pack_xg"
// age : 33
// contact : {"email":"...","phones":[...]}4. Path‑Based Operations
JsonNode root = mapper.readTree(json);
JsonNode nameNode = root.at("/user/name");
System.out.println(nameNode.asText()); // pack_xg
JsonNode secondPhone = root.at("/user/contact/phones/1");
System.out.println(secondPhone.asText()); // 010-12345678
JsonNode price = root.at("/orders/0/items/0/price");
System.out.println(price.asDouble()); // 299.99
List<Item> items = mapper.treeToValue(root.at("/orders/0/items"), new TypeReference<List<Item>>() {});
System.out.println(items);
// [Item[name=无线蓝牙耳机, price=299.99, quantity=1], Item[name=手机保护壳, price=39.5, quantity=2]]5. Modifying JSON
5.1 Update a simple field
ObjectNode rootNode = mapper.readValue(json, ObjectNode.class);
ObjectNode userObj = (ObjectNode) rootNode.get("user");
userObj.put("age", 30);
System.out.println(userObj);
// {"name":"pack_xg","age":30,"contact":{...}}5.2 Replace a nested object with a POJO
Contact newContact = new Contact("[email protected]", List.of("111111", "222222"));
userObj.putPOJO("contact", newContact);
System.out.println(userObj);
// {"name":"pack_xg","age":30,"contact":{"email":"[email protected]","phones":["111111","222222"]}}5.3 Delete a node
JsonNode removed = userObj.remove("age");
System.out.println("Removed value: " + removed.asInt()); // Removed value: 30
System.out.println(userObj);
// {"name":"pack_xg","contact":{...}}5.4 Remove all children of a node
userObj.removeAll();
System.out.println(userObj); // {}This guide demonstrates how to parse, query, convert, and mutate JSON using Jackson's JsonNode API in a Spring Boot 3.5.0 project.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
