Master Advanced Jackson Techniques in Spring Boot 3: From Files to Streaming

This article dives into advanced Jackson capabilities for Spring Boot 3, covering file, stream, byte array, URL, typed Map, JsonNode, ObjectNode, and streaming JsonParser techniques, each illustrated with concise code examples to help developers build robust, flexible JSON handling in backend services.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Advanced Jackson Techniques in Spring Boot 3: From Files to Streaming

1. Introduction

JSON is the dominant data‑exchange format and Jackson is the most popular JSON library in the Java ecosystem. This article explores advanced Jackson features that are rarely covered in basic tutorials but are essential for production‑grade Spring Boot applications.

2. Practical Cases

2.1 Convert File, InputStream and byte[] to Objects

Demonstrates reading a JSON file, an InputStream, or a byte array and mapping them to a POJO using ObjectMapper.readValue.

private final ObjectMapper objectMapper;

public ApiController(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
}

@GetMapping("/file")
public ResponseEntity<?> file() throws Exception {
    ClassPathResource resource = new ClassPathResource("book.json");
    // 1. From File
    // return ResponseEntity.ok(objectMapper.readValue(resource.getFile(), Book.class));
    // 2. From InputStream
    // return ResponseEntity.ok(objectMapper.readValue(resource.getInputStream(), Book.class));
    // 3. From byte[]
    return ResponseEntity.ok(objectMapper.readValue(resource.getContentAsByteArray(), Book.class));
}

2.2 Convert JSON from a URL

Shows how to fetch JSON directly from a URL and map it to a POJO.

@GetMapping("/url")
public ResponseEntity<?> url() throws Exception {
    URL url = URI.create("http://localhost:8080/api/file").toURL();
    return ResponseEntity.ok(objectMapper.readValue(url, Book.class));
}

2.3 Safe conversion to a typed Map

Uses TypeReference<Map<String,Object>> to obtain a generically‑typed map without unchecked warnings.

@GetMapping("/map")
public ResponseEntity<?> map() throws Exception {
    String json = "{\"id\":666,\"title\":\"Spring Boot3实战案例200讲\",\"author\":\"Pack_xg\",\"price\":70}";
    Map<String,Object> map = objectMapper.readValue(json,
        new TypeReference<Map<String,Object>>() {});
    return ResponseEntity.ok(map);
}

TypeReference injects generic type information, allowing Jackson to parse dynamic JSON safely.

2.4 Extract fields with JsonNode

Shows how to retrieve specific fields from unknown JSON structures using the tree model.

private final RestTemplate restTemplate;

@GetMapping("/jsonnode")
public ResponseEntity<?> jsonnode() throws Exception {
    URI uri = URI.create("http://localhost:8080/api/file");
    JsonNode jsonNode = restTemplate.getForObject(uri, JsonNode.class);
    return ResponseEntity.ok(Map.of(
        "id", jsonNode.get("id").asLong(),
        "title", jsonNode.get("title").asText(),
        "author", jsonNode.get("author").asText(),
        "price", jsonNode.get("price").asDouble()));
}

2.5 Dynamically build JSON with ObjectNode

ObjectNode provides mutable JSON nodes for adding, modifying, or removing fields at runtime.

@GetMapping("/objectnode")
public ResponseEntity<?> objectnode() throws Exception {
    ObjectNode objectNode = objectMapper.createObjectNode();
    objectNode.put("id", 1L);
    objectNode.put("name", "Pack_xg");
    objectNode.put("age", 33);
    return ResponseEntity.ok(objectNode);
}

2.6 Stream large JSON with JsonParser

Demonstrates low‑level streaming parsing to handle massive JSON payloads without loading the whole document into memory.

@GetMapping("/jsonparser")
public ResponseEntity<Map<String,Object>> jsonparser() throws Exception {
    String json = """
        {
          \"id\": 666,
          \"title\": \"Spring Boot3实战案例200讲\",
          \"author\": \"Pack_xg\",
          \"price\": 70,
          \"publishDate\": \"2023-01-01\"
        }
        """;
    Map<String,Object> result = new HashMap<>();
    try (JsonParser parser = new ObjectMapper().createParser(json)) {
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new IllegalStateException("Expected data to start with an object");
        }
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.currentName();
            parser.nextToken();
            switch (fieldName) {
                case "id" -> result.put(fieldName, parser.getIntValue());
                case "title", "author" -> result.put(fieldName, parser.getText());
                case "price" -> result.put(fieldName, parser.getDecimalValue());
                default -> result.put(fieldName, parser.getValueAsString());
            }
        }
    }
    return ResponseEntity.ok(result);
}

These examples illustrate how to leverage Jackson’s advanced API to handle diverse data sources, ensure type safety, and process large JSON efficiently within Spring Boot 3 applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentJSONjacksonObjectMapper
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.