Deserialization of java objects present in JSON format from a file

This post will explain how to read the serialized (JSON) form of Java objects from a file.

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();
    }
}

Main code


import java.io.File;
import java.io.FileReader;
import java.io.IOException;

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

public class JsonbDemo4 {
    public static void main(String[] args) throws IOException {
        File file = new File("output2.txt");
        Jsonb jsonb = JsonbBuilder.create();
        try(FileReader fr = new FileReader(file)) {
            Person person = jsonb.fromJson(fr, Person.class);
            System.out.println(person);
        }
    }
}
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