json file I/O with pretty print format using gson in java?
Asked Answered
B

2

6
  • 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
Biota answered 14/9, 2017 at 5:3 Comment(2)
Welcome to Stack Overflow! Please take the tour to see how the site works and what questions are on topic here, and edit your question accordingly. See also: Why is "Can someone help me?" not an actual question?Curlew
Possible duplicate of Pretty-Print JSON in JavaFleming
J
7

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.

Jersey answered 14/9, 2017 at 6:47 Comment(1)
Minor comment, since the snippet uses try-with-resources (available from Java 7), calling writer.close() here is redundant (invoked automatically). Generally speaking (if not using try-with-resources), a good practice for closing a resource is to use the finally block, to avoid potential resource leak in case of exception..Taegu
R
1

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));
Revisionist answered 14/9, 2017 at 5:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.