Tuesday, November 12, 2013

Google Gson

Google gson is one of the powerful tool which you can convert your Java Object to the JSON and vice versa. Other toll is jackson which you can convert your Java Object to the JSON as well.

I have done a small program which has been done with Google Gson.

Main Gson Implementation Class
package rezg.camel.client.util;

import com.google.gson.Gson;

public class JsonConvertor <t> {

 private T obj;

//This method will convert a passing Object to a Json Strcuture
public String convertToJson(T myObj) {
  Gson gson = new Gson();
  String retVal = gson.toJson(myObj);
  return retVal;
 }

//This method will convert a Json String to an passing Object Type
 public T convertToObject(String jsonString, Class<t> retVal) {
  Gson gson = new Gson();
  obj = gson.fromJson(jsonString, retVal);
  return obj;
 }
}
 
Convert Json String to a Java Object
 private static Customer getObject(String jsonStr) {

  JsonConvertor<Customer> cusJsonConvertor = new JsonConvertor<Customer>();

  Customer myCustomer = cusJsonConvertor.convertToObject(jsonStr,
    Customer.class);

  System.out.println("myCustomer.toString() " + myCustomer.toString());

  return myCustomer;
 }
Convert Java Object to a Json String
 private static String getJson() {

  Customer customer = new Customer();
  customer.setAddress("My Company Address");
  customer.setName("My Comppany");
  customer.setAge(45);

  List&ltString> employees = new ArrayList&ltString>();
  employees.add("Adam");
  employees.add("Jhon");
  employees.add("Anne");
  customer.setEmployees(employees);

  List&ltInventory> invetories = new ArrayList&ltInventory>();
  Inventory inv = new Inventory();
  inv.setAmount("2500");
  invetories.add(inv);

  inv = new Inventory();
  inv.setAmount("3000");
  invetories.add(inv);

  inv = new Inventory();
  inv.setAmount("4000");
  invetories.add(inv);

  customer.setInventories(invetories);

  JsonConvertor&ltCustomer> cusJsonConvertor = new JsonConvertor&ltCustomer>();
  String jsonStr = cusJsonConvertor.convertToJson(customer);

  return jsonStr;
 }