Java ObjectMapper Examples in 5 Minutes

The Java ObjectMapper is part of the Jackson library. It provides an easy way to serialize Java to JSON:

String jsonString = objectMapper.writeValueAsString(new User());

And deserialize JSON to Java:

User user = objectMapper.readValue(jsonString, User.class);

What is serialization anyways?

Serialization converts language specific objects into platform independent byte streams. This makes it possible to transfer data structures from one app to another.

If you've implemented a RESTful web service then you've worked with serialization. Web browsers can send/receive JSON objects to a web server because of serialization.

Put another way, you can't just send a Java POJO to a web browser. The Java class is specific to the Java runtime. Using a parser library like Jackson allows you to serialize or "convert" the Java class into a byte stream that can be sent over a wire...

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(new Person("Sam", "Erickson"));
System.out.println(jsonString); //"{"first":"Sam", "last":"Erickson"}"

By using the Jackson ObjectMapper class, you can easily convert Java POJO like Person to JSON string format.

Just like you can use ObjectMapper to serialize JSON strings, you can use it to deserialize JSON into Java classes...

String jsonString = "{\"first\": \"Sam\", \"last\": \"Erickson\"}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println(person.first); //"Sam"
System.out.println(person.last); //"Erickson"

How does Java ObjectMapper work?

How Jackson ObjectMapper serialization works

When you call writeValue() or a similar method the Object mapper creates a JsonGenerator. This is what's actually responsible for writing the JSON output.

The JsonGenerator is created via a JsonFactory. The JsonFactory allows for the creation of JsonGenerators with different output sources. This means you can serialize JSON output to a file, output stream, etc. using the ObjectMapper class.

Using standard java.io libraries the JsonGenerator evaluates each field and value for the input object and writes to an output buffer.

How Jackson ObjectMapper deserialization works

The same JsonFactory creates JsonParsers which parse JSON from different sources. For example a parser exists for JSON input strings as well as character arrays.

The various parsers generate corresponding Java POJO classes for the provided input class. While each parser implementation behaves differently, they essentially utilize java.io libraries to read input sources and map them to input classes..

Person person = objectMapper.readValue(jsonString, Person.class);

Notice how the object mapper's readValue() method takes an input string jsonString and input class Person.class.

Jackson Annotations

In addition to the ObjectMapper class, the Jackson library also provides some convenient annotations for working with JSON serialization.

@JsonIgnore

When you annotate a field with @JsonIgnore it will be ignored in the serialization process...

package com.example.demo;
import com.fasterxml.jackson.annotation.JsonIgnore;

public class User {
    public User(String username, String password){
        this.username = username;
        this.password = password;
    }
    public String username;

    @JsonIgnore
    public String password;
}
String jsonString = "{\"username\": \"abc\", \"password\": \"123\"}";
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(jsonString, User.class);
System.out.println(user.username); //"abc"
System.out.println(user.password); //null

Notice how the password field is not included when deserializing the jsonString.

The same applies to serializing as well..

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(new User("abc","123"));
System.out.println(jsonString); //{"username":"abc"}

@JsonProperty

By default, JSON properties map to field names. If you want rename a particular field for serialization you can do so using @JsonProperty

package com.example.demo;
import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    public User(String username, String password){
        this.username = username;
        this.password = password;
    }
    public String username;

    @JsonProperty("pWord")
    public String password;
}
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(new User("abc","123"));
System.out.println(jsonString); //{"username":"abc", "pWord":"123"}

Notice how the password field serializes as pWord

The same, of course, applies to deserializing objects as well.

Conclusion

The ObjectMapper is part of the Jackson library. The Jackson library is one of the most popular JSON parsing libraries in the Java programming language.

Using the Jackson ObjectMapper you can easily serialize Java classes to JSON representations and deserialize JSON representations into Java classes. In this sense, you can "convert" between the two using ObjectMapper.

Frameworks like Spring inherently use Jackson to serialize request/response data. When using Spring Boot, Jackson serialization automatically happens when you include @EnableWebMvc in your application. This removes the need to interact directly with the ObjectMapper for many use cases.

Using Jackson Annotations with data models gives developers more fine grained control over how objects get serialized/deserialized with the ObjectMapper.

Your thoughts?

|

ObjectMapper is very popular and used by many different projects to implement serializers and deserializers in Java.

For example, the Spring Kafka JsonDeserializer uses ObjectMapper in its own implementation. The Jackson library is very popular and remains a "de-facto" method of parsing/serializing/deserializing and working with JSON in general...

|

great read..thank you! :)

|

much better than other explanations out there...