1. Introduction
JSON Serialization in Java, which is just a fancy term for turning Java objects into JSON format, is something we do a lot when we’re coding in Java. But here’s the thing, sometimes our Java objects have null values, and we need to decide what to do with them when we’re converting to JSON. If we just ignore these null values and leave them out of our JSON, it can mess up our data. It’s like leaving out a piece of a puzzle – the picture isn’t complete without it.
So, it’s super important to handle these null values correctly when we’re doing our JSON object serialization and deserialization.
In this tutorial, we’ll get into effective strategies for including null values in JSON serialization in Java objects. This way, our data stays accurate and reliable, just like we want it to be.
2. Dependencies
Before we start using Jackson and Gson libraries, we need to add their dependencies in our project. Here’s how you can do it:
2.1. Maven Dependencies
Add the following lines to your pom.xml file to include Jackson and Gson libraries:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
2.2. Gradle
Similarly, add the following lines to your gradle file to include Jackson and Gson libraries:
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.17.0'
implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
3. Model
Imagine we’re designing a system to keep track of students. Each student’s information is encapsulated in a Java object, containing details such as name, email, and age. However, not all students may have an email address.
When converting this student information into JSON for saving or sending, it’s crucial to include null values for any missing email addresses. This helps keep our data consistent.
Let’s define the Student class:
public class Student {
@JsonProperty
private final String name;
@JsonProperty
private final String email;
@JsonProperty
private final int age;
public Student(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
// Getters and Setters...
}
Here, the Student class has fields for name, email, and age, which we set up using a constructor method. The toString() method also gives a string version of the object in a JSON-like way, making it easy to check.
It’s important to mention that using @JsonProperty makes sure all the right fields get included in the JSON output, including null values when needed.
4. JSON Serialization
We can convert Java objects into JSON format using two popular libraries.
4.1. Using Jackson
Jackson is a famous Java tool for dealing with JSON. By default, it excludes null values from the JSON marshalling.
But, we can use Jackson’s tools to include null as value:
String expectedJson = "{\"name\":\"Raj\",\"email\":null,\"age\":20}";
Student obj = new Student("Raj", null, 20);
@Test
public void checkNullFieldWithJackson() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
String json = mapper.writeValueAsString(obj);
assertEquals(expectedJson, json);
}
In this example, we first make the expectedJson string and then we make a Student object with the values “Raj”, null, and 20.
After that, we set up an ObjectMapper to always include null values during JSON marshalling by using setSerializationInclusion(JsonInclude.Include.ALWAYS). This careful setup makes sure that even if the email is null, it still shows up right in the JSON output.
Lastly, we use assertEquals() to verify that the json string matches the expectedJson string.
4.2. Using Gson
Gson is another popular Java library for JSON marshalling and unmarshalling. It also lets us include null values. Here’s how:
@Test
public void checkNullFieldWithGson() {
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(obj);
assertEquals(expectedJson, json);
}
Here, we use GsonBuilder to make a Gson object and use serializeNulls() to include null values to be serialized. This approach guarantees that fields with null value, such as the email, are accurately included in the JSON output.
5. Conclusion
Properly handling null values is paramount when converting Java objects into JSON format. This guide has explored methods to ensure null values are appropriately included during serialization in java, using both Jackson and Gson libraries.
By following these practices, we can maintain the integrity and accuracy of our data representations.