The Java ObjectMapper is a part of the Jackson library, providing a straightforward way to serialize Java objects to JSON and deserialize JSON back to Java objects.
String jsonString = objectMapper.writeValueAsString(new User());
And deserialize JSON to Java:
User user = objectMapper.readValue(jsonString, User.class);
Key Takeaways
- The
ObjectMapperclass in the Jackson library facilitates easy serialization and deserialization between Java and JSON. - Serialization converts Java objects into JSON strings, making data exchange across platforms feasible.
- Using Jackson annotations, you can customize how Java objects are serialized and deserialized.
What is Serialization?
Serialization is the process of converting Java-specific objects into platform-independent byte streams. This enables data to be transferred across different systems or stored efficiently. In web applications, serialization is what allows JSON data to be sent and received over HTTP, facilitating interactions between client-side and server-side applications.
If you've built a RESTful API, you've likely worked with serialization. By converting Java objects to JSON, they become consumable by web clients that aren't running Java. Serialization leverages libraries like Jackson to abstract this conversion process effectively.
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(new Person("Sam", "Erickson"));
System.out.println(jsonString); // "{\"first\":\"Sam\", \"last\":\"Erickson\"}"
This snippet demonstrates using Jackson's ObjectMapper to convert a Java POJO into a JSON string.
How Does Java ObjectMapper Work?
Serialization with Jackson ObjectMapper
When you serialize an object with ObjectMapper, it employs a JsonGenerator to produce the JSON. This generator is crafted using a JsonFactory, which makes it flexible enough to output JSON to various destinations such as files or network streams.
The JsonGenerator inspects each field of your Java object, serializing them into JSON format using standard Java I/O operations.
Deserialization with Jackson ObjectMapper
Conversely, ObjectMapper creates JsonParser instances via a JsonFactory to handle JSON input from multiple sources. These parsers read JSON data and convert it back into Java objects. Each JsonParser variation is adept at processing different input forms, such as strings or streams.
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"
Here, the readValue() method takes a JSON string and a class type to map the JSON properties directly onto the Java object's fields.
Jackson Annotations
Beyond the ObjectMapper, Jackson provides annotations to control serialization behavior more precisely.
@JsonIgnore
Fields marked with @JsonIgnore are excluded from serialization and deserialization:
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\"}";
User user = objectMapper.readValue(jsonString, User.class);
System.out.println(user.username); // "abc"
System.out.println(user.password); // null
Notice the password field is ignored during both serialization and deserialization.
@JsonProperty
Use @JsonProperty to specify the JSON property name for a field:
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;
}
String jsonString = objectMapper.writeValueAsString(new User("abc","123"));
System.out.println(jsonString); // "{\"username\":\"abc\", \"pWord\":\"123\"}"
Here, the password field is serialized with the JSON key pWord.
Conclusion
Jackson's ObjectMapper is a robust tool within the popular JSON parsing library. It simplifies transforming Java objects to JSON and vice versa, offering flexibility that scales across various applications.
Spring and other frameworks often integrate Jackson to manage data transfer automatically, reducing the programmer's burden to directly handle the ObjectMapper. Using annotations, developers have fine-tuned command over JSON data representation.
FAQ
What are typical use cases for Jackson's ObjectMapper?
ObjectMapper is typically used in RESTful services, configuration parsing, and any scenario requiring data serialization and deserialization.
How does ObjectMapper handle complex nested objects?
ObjectMapper can serialize and deserialize complex nested structures without additional configuration, provided you have appropriately structured Java classes.
Can ObjectMapper be used for XML?
Yes, Jackson also supports XML through the XmlMapper class, which operates similarly to ObjectMapper but for XML data formats.
