Deserialization of java objects from JSON

This post explains de-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

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


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;
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.toString();

Below is the main code

1  import javax.json.bind.Jsonb;
2  import javax.json.bind.JsonbBuilder;
4  public class JsonbDemo3 {
5   public static void main(String[] args) {
6       Jsonb jsonb = JsonbBuilder.create();
7       String input = "{\"age\":10,\"fName\":\"fName1\",\"lName\":\"lName1\"}";
8       Person person = jsonb.fromJson(input, Person.class);
9       System.out.println(person);
10  }
11 }

At line 6 we create an instance of Jsonb using the JsonbBuilder’s staic method create

At line 8 we convert the json string in the input variable to java object using the fromJson method available in the Jsonb class.

The fromJson method requires two parameters
1) the json string
2) the class details



Leave a Reply