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

Leave a Reply