Convert Java to JSON and JSON to JAVA using gson
Gson Java library has been developed which can be used to convert either JSON to Java or Java to JSON. Gson library can also be used with arbitrary Java objects which includes any existing objects if that source code is not available.
It has two methods:
- toJson() – Converts Java to JSON object
- fromJson() – Converts JSON to java object
Below is sample java class to convert Java to JSON and JSON to Java object. Only you need latest version of gson-2.2.2.jar in your class path this can be download form google site here or download gson-2.2.2.jar in the bottom of the page download link:
package com.javahonk; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JavaJsonTest { public static void main(String[] args) { List<Employee> employeeList = new ArrayList<Employee>(); for (int i = 0; i < 2; i++) { Employee employee = new Employee(); employee.setName("John Landy"); employee.setPosition("System Architect"); employee.setOffice("NY"); employeeList.add(employee); } //Java to JSON conversion Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(employeeList); System.out.println("Java to JSON:\n"); System.out.println(json); //JSON to java conversion System.out.println("\nJSON to java conversion\n"); Employee[] employee = gson.fromJson(json, Employee[].class); System.out.println("Size of JSON object:" +employee.length+"\n"); for (Employee employee2 : employee) { System.out.println("Name: "+employee2.getName() +" Position: "+employee2.getPosition() +" Office: "+employee2.getOffice()); } } } class Employee{ private String name; private String position; private String office; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } }
Output:
Download gson-2.2.2.jar