:
public class Employee implements Serializable {
    private String lastName;
    private String address;
    private int id;
    private String name;
}
I want to create a json file with the exact following content
 [
            {
                "id":1,
                "name": "John",
                "lastName": "Doe",
                "address": "NY City"
            },
            {
                "id":2,
                "name": "John",
                "lastName": "Doe",
                "address": "Canada"
            },
            {
                "id":3,
                "name": "John",
                "lastName": "Doe",
                "address": "Las Vegas"
            },
    ]
{"id":1,"name": "John","last": "Doe","address": "NY City"} {"id":2,"name": "John","last": "Doe","address": "Canada"} {"id":3,"name": "John","last": "Doe","address": "Las Vegas"}
but that's not what I want my final program to do.
[ { "id":1, "name": "John", "lastName": "Doe", "address": "NY City" }, { "id":2, "name": "John", "lastName": "Doe", "address": "Canada" }, { "id":3, "name": "John", "lastName": "Doe", "address": "Las Vegas" }, ]
but I don't know how to create and write this json file with a java program as an array of Person objects, where every Person object is a part of this list or array with pretty print format, as the one I hard coded and am able to read. How can I do that in an elegant way?
EDIT--- Thanks a lot to @Shyam!
This is my final code, hope it helps someone.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class TestFileOfGsonWriter {
    Gson gson ;
    String filePath ;
    BufferedReader bufferToReader ;
    public TestFileOfGsonWriter()
    {
        this.filePath = 
                "C:\\FileOfGsonSingleListOfEmployees\\employees.json" ;
    }
    public List<Employee> createEmployees()
    {
        Employee arya = new Employee("Stark", "#81, 2nd main, Winterfell", 2, "Arya");
        Employee jon = new Employee("Snow", "#81, 2nd main, Winterfell", 1, "Jon");
        Employee sansa = new Employee("Stark", "#81, 2nd main, Winterfell", 3, "Sansa");
        List<Employee> employees = new ArrayList<>();
        employees.add(jon);
        employees.add(arya);
        employees.add(sansa);
        return employees ;
    }
    public void jsonWriter(List<Employee> employees, String filePath)
    {
        this.gson = new GsonBuilder().setPrettyPrinting().create();
        try(FileWriter writer = new FileWriter(filePath))
        {
            gson.toJson(employees,writer);
            writer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    public void showEmployeeObjects()
    {
        try {
            List<Employee> employees = this.getAllEmployees();
            employees.forEach(e -> Employee.showEmployeeDetails(e));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public ArrayList<Employee> getAllEmployees() throws IOException
    {
        FileReader reader = new FileReader(this.filePath);
        this.bufferToReader = new BufferedReader(reader) ;
        ArrayList <Employee> employees = this.gson.fromJson(getJson(), 
                new TypeToken<ArrayList<Employee>>(){}.getType());
        return employees ;
    }
    private String getJson() throws IOException
    {
        StringBuilder serializedEmployee = new StringBuilder();
        String line ;
        while ( (line = this.bufferToReader.readLine()) != null )
        {
            serializedEmployee.append(line);
        }
        this.bufferToReader.close();
        return serializedEmployee.toString();
    }
    public static void main(String[] args) {
        TestFileOfGsonWriter testWriting = new TestFileOfGsonWriter() ;
        List<Employee> employees = testWriting.createEmployees();
        testWriting.jsonWriter(employees, testWriting.filePath);
        testWriting.showEmployeeObjects();
    }
}
I modified my Employee class so it would match with his dummy objects which were better I think, this is how it looks now.
import java.io.Serializable;
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    String name ;
    String address;
    String lastName ;
    int id ;
    public static void showEmployeeDetails(Employee e)
    {
        System.out.println();
        System.out.println("Employee's name: "+e.name);
        System.out.println("Employee's last name"+e.lastName);
        System.out.println("Employee's address: "+e.address);
        System.out.println("Employee's ID: "+e.id);
    }
    public Employee(String myName, String myAddress, int myId, String myLastName)
    {
        this.name = myName ;
        this.address = myAddress;
        this.lastName = myLastName;
        this.id = myId ;
    }
}
So, the json file the program creates looks exactly how I wanted:
[
  {
    "name": "Snow",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Jon",
    "id": 1
  },
  {
    "name": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Arya",
    "id": 2
  },
  {
    "name": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Sansa",
    "id": 3
  }
]
and finally, this is the output:
Employee's name: Snow
Employee's last nameJon
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 1
Employee's name: Stark
Employee's last nameArya
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 2
Employee's name: Stark
Employee's last nameSansa
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 3
                As you are new, I'll quickly walk you through the process of writing a List of Employee objects to a JSON file with pretty printing:
Step 1: Create a method that takes in a List and a String filePath:
public void jsonWriter(List<Employee> employees, String filePath)
Step 2: Build a Gson Object with pretty printing enabled:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Step 3: Write your List<Employee> to a JSON file in the given filePath using a FileWriter:
       try(FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(employees, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
Finally the entire method should look something like this:
public void jsonWriter(List<Employee> employees, String filePath) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try(FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(employees, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Step 4: Now, build your Employee objects, add them to a List and call this method with the appropriate filePath
        Employee arya = new Employee("Stark", "#81, 2nd main, Winterfell", 2, "Arya");
        Employee jon = new Employee("Snow", "#81, 2nd main, Winterfell", 1, "Jon");
        Employee sansa = new Employee("Stark", "#81, 2nd main, Winterfell", 3, "Sansa");
        List<Employee> employees = new ArrayList<>();
        employees.add(jon);
        employees.add(arya);
        employees.add(sansa);
        jsonWriter(employees, "C:/downloads/employees.json");
After running this code, the contents of JSON file will look something like this:
[
  {
    "lastName": "Snow",
    "address": "#81, 2nd main, Winterfell",
    "id": 1,
    "name": "Jon"
  },
  {
    "lastName": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "id": 2,
    "name": "Arya"
  },
  {
    "lastName": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "id": 3,
    "name": "Sansa"
  }
]
I hope this will help you in your learning process.
Note: I've used some random Employee names and details. You can replace it with your required details.
Firstly store those objects into a list of objects. Then add this line of code for pretty print.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson (list));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With