Serialization of Java objects to JSON

This post explains serialization of java objects to JSON using new Java JSONB api. We need the following jars to run the below example
1) javax.json-1.1.jar
2) jsonb-api-1.0.0.jar
3) yasson-1.0.jar

yasson-1.0.jar is reference implemenation which can be obtained from the below link
http://json-b.net/download.html

In this example we will serialize the Person object, below is the class details of Person class

Person


public class Person {
    private String fName;
    private String lName;
    private int age;
    
    public String getfName() {
        return fName;
    }
    public void setfName(String fName) {
        this.fName = fName;
    }
    public String getlName() {
        return lName;
    }
    public void setlName(String lName) {
        this.lName = lName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(fName).append(":");
        sb.append(lName).append(":");
        sb.append(age);
        
        return sb.toString();
    }
}

Below is the main code

Main Code


1  import javax.json.bind.Jsonb;
2  import javax.json.bind.JsonbBuilder;
3  
4  public class JsonbDemo1 {
5   public static void main(String[] args) {
6       Person person = new Person();
7       person.setfName("fName");
8       person.setlName("lName");
9       person.setAge(10);
10      
11      Jsonb jsonb = JsonbBuilder.create();
12      String result = jsonb.toJson(person);
13      System.out.println(result);
14  }
15 }

At line 6 to 9 we create an instance of Person class to be serialized.

At line 11 we use JsonBuilder’s static method create to obtain an instance of Jsonb class

JsonBuilder class is used to create and configure the Jsonb instance using the default configuration parameters.

The configuration parameters can be user configured which I will explain in future posts.

Its through Jsonb instance we deserialize or serialize java objects.

We serialize java object to json using Jsonb’s toJson method. Refer to line 12. The return value is a string which is printed at line 13.

Output

{“age”:10,”fName”:”fName”,”lName”:”lName”}

Leave a Reply