javaintermediate

Jackson — JSON Serialization and Parsing

Parse and generate JSON with Jackson: ObjectMapper, annotations, custom serializers, and streaming.

java
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDate;
import java.util.*;

public class JacksonDemo {
    // DTO with annotations
    @JsonIgnoreProperties(ignoreUnknown = true)
    record User(
        @JsonProperty("user_id") Long id,
        String name,
        @JsonFormat(pattern = "yyyy-MM-dd") LocalDate joinDate,
        @JsonInclude(JsonInclude.Include.NON_NULL) String nickname
    ) {}

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // Object to JSON
        User user = new User(1L, "Alice", LocalDate.of(2024, 1, 15), null);
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
        // {"user_id":1,"name":"Alice","joinDate":"2024-01-15"}

        // Pretty print
        String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);

        // JSON to Object
        String input = "{\"user_id\":2,\"name\":\"Bob\",\"joinDate\":\"2024-06-01\",\"extra\":true}";
        User parsed = mapper.readValue(input, User.class);
        System.out.println(parsed.name()); // Bob

        // JSON to List
        String arrayJson = "[{\"user_id\":1,\"name\":\"A\"},{\"user_id\":2,\"name\":\"B\"}]";
        List<User> users = mapper.readValue(arrayJson, new TypeReference<List<User>>() {});

        // JSON to Map
        Map<String, Object> map = mapper.readValue(input, new TypeReference<>() {});
        System.out.println(map.get("name")); // Bob

        // Convert between types
        Map<String, Object> userMap = mapper.convertValue(user, new TypeReference<>() {});
    }
}

Use Cases

  • REST API request and response serialization
  • Parsing external API JSON responses
  • Converting between JSON, maps, and Java objects

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.