Java

Jackson — Basic ObjectMapper

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`com.fasterxml.jackson.databind.ObjectMapper` is the JSON standard for Java. Construct once (it's expensive + thread-safe) and reuse for every serialization in your app.
Java
Raw
// pom.xml: com.fasterxml.jackson.core:jackson-databind
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.List;

class Demo {
    static final ObjectMapper MAPPER = new ObjectMapper()
        .enable(SerializationFeature.INDENT_OUTPUT);   // pretty-print

    record User(int id, String name, String email) {}

    public static void main(String[] args) throws Exception {
        // Object → JSON
        var user = new User(42, "Alice", "a@x.com");
        String json = MAPPER.writeValueAsString(user);
        System.out.println(json);
        // {
        //   "id" : 42,
        //   "name" : "Alice",
        //   "email" : "a@x.com"
        // }

        // JSON → Object
        String input = """
            {"id": 7, "name": "Bob", "email": "b@x.com"}
            """;
        User parsed = MAPPER.readValue(input, User.class);
        System.out.println(parsed);

        // Generic types via TypeReference
        String arr = "[{\"id\":1,\"name\":\"a\"},{\"id\":2,\"name\":\"b\"}]";
        var users = MAPPER.readValue(arr,
            new com.fasterxml.jackson.core.type.TypeReference<List<User>>() {});
        System.out.println(users);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.