Serialization of null values when converting from java object to json format

In this post I will explain how serialization of null values feature can be turned on or off.

Below is the class structure of the object to be serialized

Student


1  import javax.json.bind.annotation.JsonbProperty;
2  
3  public class Student {
4   private int id;
5   private String name;
6   private Integer rollnum;
7   
8   public int getId() {
9       return id;
10  }
11  public void setId(int id) {
12      this.id = id;
13  }
14  public String getName() {
15      return name;
16  }
17  
18  @JsonbProperty(nillable=false)
19  public void setName(String name) {
20      this.name = name;
21  }
22  
23  @JsonbProperty(nillable=true)
24  public Integer getRollnum() {
25      return rollnum;
26  }
27  public void setRollnum(Integer rollnum) {
28      this.rollnum = rollnum;
29  }
30 }

Name and Roll number are the two fields which can be null in a Student class instance.

We toggle the serialization of null values feature by enabling/disabling the nillable attribute of JsonbProperty annotation.

In the our example at line 18 we disabled the serialization of null value and at line 23 we enabled it.

So when we serialize the object, the null value for rollnum will be serialized, whereas null value of name field will not be serialized. Below is the output

Output

{“id”:1,”rollnum”:null}

Main Code


import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

public class JsonbDemo7 {
    public static void main(String[] args) {
        Jsonb jsonb = JsonbBuilder.create();
        
        Student student1 = new Student();
        student1.setId(1);
        student1.setName(null);
        student1.setRollnum(null);
        String result = jsonb.toJson(student1);
        System.out.println(result);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s