Serialization of java object in JSON format to a file

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

Main Code


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

public class JsonbDemo2 {
    public static void main(String[] args) throws IOException {
        Person person = new Person();
        person.setfName("fName");
        person.setlName("lName");
        person.setAge(10);
        
        Jsonb jsonb = JsonbBuilder.create();
        
        File file = new File("output2.txt");
        try(FileWriter fw = new FileWriter(file)) {
            jsonb.toJson(person,fw);
        }
    }
}
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