- I already know how gson works and also know how to enable pretty print.
- I want to use gson and not simplejson.
- The problem I had is that I wasn't able to create a file consisting of a List of Employee objects.
- I've seen every other java threads in stackoverflow, mkyong, google's github and many others sites and I still wasn't able to accomplish this simple thing.
- I already know how to read a file with this specific format but I wasn't able to write it.
- The problem is I was not able to combine all these things together in a program.
- A List of objects in gson with pretty print enabled must have the proper indentation, and every object must be separated with a comma and those objects must be wrapped between [ ] .
- The problem explained with code
:
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"
            },
    ]
- I managed to create and write a json file of Person objects (as gson json Person objects), and read it, but again only as Person objects, where every line is an independent object, not a part of a List or Array of Person objects, like this
{"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.
- I was also able to hard code a file with the following info and format and successfully obtain the Person objects
[ { "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
 
     
    