Master Advanced JSON Handling in Spring Boot 3 with Jackson
This article walks through advanced Jackson techniques for JSON processing in Spring Boot 3, including path queries, multi‑value extraction, view control, dynamic property handling, object unwrapping, and raw JSON insertion, each illustrated with concise JUnit test examples and expected outputs.
Environment: Spring Boot 3.4.2
1. Introduction
The article demonstrates advanced JSON processing capabilities using the Jackson library in Spring Boot 3, covering JSON path queries, batch value extraction, view‑based field control, dynamic attribute handling, object flattening, and raw JSON insertion.
2. Practical Examples
2.1 findValue to locate a value
@Test
public void test1() throws Exception {
String json = """
{
"user": {
"id": 1,
"name": "Pack_xg",
"details": {
"email": "[email protected]",
"phone": "18999999999"
}
}
}""";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
String email = rootNode.findValue("email").asText();
System.err.println(email);
}Output:
[email protected]2.2 Gracefully handling missing keys
@Test
public void test2() throws Exception {
String json = """
{
"user": {
"id": 1,
"name": "Pack_xg",
"details": {
"phone": "18999999999"
}
}
}""";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
JsonNode emailNode = rootNode.findValue("email");
System.err.println(emailNode);
}Output:
null2.3 Using findValues() for arrays
@Test
public void test3() throws Exception {
String json = """
{
"users": [
{ "id": 1, "name": "pack", "details": { "email": "[email protected]" } },
{ "id": 2, "name": "xg", "details": { "email": "[email protected]" } }
]
}""";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
List<String> emails = rootNode.findValues("email")
.stream()
.map(JsonNode::asText)
.toList();
System.err.println(emails);
}Output:
[[email protected], [email protected]]2.4 Accessing deep nested keys with at()
@Test
public void test4() throws Exception {
String json = """
{
"company": {
"dept": {
"team": {
"lead": {
"name": "Pack_xg",
"details": {
"email": "[email protected]"
}
}
}
}
}
}""";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
String email = rootNode.at("/company/dept/team/lead/details/email").asText();
System.err.println(email);
}Output:
[email protected]2.5 Controlling fields with @JsonView
public class User {
public interface PublicView {}
public interface InternalView extends PublicView {}
@JsonView(PublicView.class)
private String name;
@JsonView(InternalView.class)
private String email;
@JsonView(InternalView.class)
private String password;
// constructor, getters, setters omitted for brevity
}
@Test
public void test5() throws Exception {
User user = new User("Pack_xg", "[email protected]", "123456");
ObjectMapper mapper = new ObjectMapper();
String publicJson = mapper.writerWithView(User.PublicView.class).writeValueAsString(user);
System.err.println(publicJson);
String internalJson = mapper.writerWithView(User.InternalView.class).writeValueAsString(user);
System.err.println(internalJson);
}Output (public view): {"name":"Pack_xg"} Output (internal view):
{"name":"Pack_xg","email":"[email protected]","password":"123456"}2.6 Handling unknown properties with @JsonAnySetter / @JsonAnyGetter
public class DynamicObject {
private Long id;
private String name;
private Map<String, Object> properties = new HashMap<>();
@JsonAnySetter
public void set(String name, Object value) {
properties.put(name, value);
}
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
}
}
@Test
public void test6() throws Exception {
String json = """
{
"id": 666,
"name": "Pack_xg",
"age": 33,
"details": {
"phone": "18999999999",
"addr": "中国"
}
}""";
ObjectMapper objectMapper = new ObjectMapper();
DynamicObject user = objectMapper.readValue(json, DynamicObject.class);
System.out.println(user);
String serializedJson = objectMapper.writeValueAsString(user);
System.out.println("
重新序列化后的 JSON:");
System.out.println(serializedJson);
}The serialized JSON includes the dynamic properties captured by @JsonAnySetter.
2.7 Flattening nested objects with @JsonUnwrapped
public class Order {
private Long id;
private String orderNo;
@JsonUnwrapped
private Address address;
}
public class Address {
private String provice;
private String city;
private String county;
}
@Test
public void test7() throws Exception {
Order order = new Order(1L, "XP-00001", new Address("新疆", "乌鲁木齐", "天山区"));
ObjectMapper objectMapper = new ObjectMapper();
System.err.println(objectMapper.writeValueAsString(order));
}Output:
{"id":1,"orderNo":"XP-00001","provice":"新疆","city":"乌鲁木齐","county":"天山区"}2.8 Inserting raw JSON with @JsonRawValue
public class Product {
private String name;
private BigDecimal price;
@JsonRawValue
private String details;
}
@Test
public void test8() throws Exception {
Product product = new Product();
product.setName("Spring Boot3实战案例200讲");
product.setPrice(new BigDecimal("70"));
product.setDetails("{\"author\":\"pack_xg\",\"page_count\":1000}");
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.err.println(mapper.writeValueAsString(product));
}Output includes the raw JSON fragment without escaping:
{"name":"Spring Boot3实战案例200讲","price":70,"details":{"author":"pack_xg","page_count":1000}}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.
