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


1  import javax.json.bind.annotation.JsonbProperty;
3  public class Student {
4   private int id;
5   private String name;
6   private Integer rollnum;
8   public int getId() {
9       return id;
10  }
11  public void setId(int id) {
12 = id;
13  }
14  public String getName() {
15      return name;
16  }
18  @JsonbProperty(nillable=false)
19  public void setName(String name) {
20 = name;
21  }
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



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();
        String result = jsonb.toJson(student1);

Leave a Reply

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

You are commenting using your 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