Table of Contents

Basic Gson

Add Gson Dependency

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Assumption

Assume we have a Company class, and a Staff class such that Company has a name, a start date, and a list of staff, and the staff has a name, and a salary field. We use the following code to create the Java objects.

Company company = new Company();
    company.setName("ABC Company");
    company.setStartDate(new Date());
    Staff staff1 = new Staff();
    staff1.setName("Staff 1");
    staff1.setSalary(10000.0);
    Staff staff2 = new Staff();
    staff2.setName("Staff 2");
    staff2.setSalary(20000.0);
    Staff staff3 = new Staff();
    staff3.setName("Staff 3");
    staff3.setSalary(30000.0);
    Staff staff4 = new Staff();
    staff4.setName("Staff 4");
    staff4.setSalary(40000.0);
    List<Staff> list = new ArrayList<Staff>();
    list.add(staff1);
    list.add(staff2);
    list.add(staff3);
    list.add(staff4);
    company.setStaffs(list);

To Json

   Gson gson = new Gson();
   String json = gson.toJson(company);
   System.out.println(json);

The result would be

{"name":"ABC Company","startDate":"Aug 13, 2019 2:39:50 PM","staffs":[{"name":"Staff 1","salary":10000.0},{"name":"Staff 2","salary":20000.0},{"name":"Staff 3","salary":30000.0},{"name":"Staff 4","salary":40000.0}]}

From Json

Assume we user the output from above to create a Company object:

Company testCompany = gson.fromJson(json, Company.class);