Sunday 18 September 2016

gson: JSON Utility class


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author harikrishna_gurram
 *
 */
public class JSONUtil {
 private static Gson gson = new Gson();
 private static Gson exclusedGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
 private static Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();

 /**
  * @param obj
  * @return json string of this object.
  */
 public static String getJson(Object obj) {
  return gson.toJson(obj);
 }

 /**
  * @param obj
  * @return json string of this object.
  */
 public static String getOnlyExposedJson(Object obj) {
  return exclusedGson.toJson(obj);
 }

 /**
  * @param obj
  * @return json string of this object (Pretty json).
  */
 public static String getPrettyJson(Object obj) {
  return prettyGson.toJson(obj);
 }

 /**
  * Convert given json string to object.
  * 
  * @param json
  * @param obj
  * @return an object by populating properties with json data.
  */
 public static <T> T getObject(String json, Class<T> clazz) {
  return gson.fromJson(json, clazz);
 }

}

Previous                                                 Next                                                 Home

No comments:

Post a Comment