/src/main/java/com/google/ie/common/util/GsonUtility.java

http://thoughtsite.googlecode.com/ · Java · 181 lines · 88 code · 20 blank · 73 comment · 2 complexity · 82491626b55412b92e2b5a9f5dd41927 MD5 · raw file

  1. /* Copyright 2010 Google Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS.
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License
  14. */
  15. package com.google.ie.common.util;
  16. import com.google.gson.ExclusionStrategy;
  17. import com.google.gson.FieldAttributes;
  18. import com.google.gson.Gson;
  19. import com.google.gson.GsonBuilder;
  20. import com.google.gson.JsonElement;
  21. import com.google.gson.JsonObject;
  22. import com.google.gson.JsonPrimitive;
  23. import com.google.gson.JsonSerializationContext;
  24. import com.google.gson.JsonSerializer;
  25. import org.apache.commons.lang.StringUtils;
  26. import java.lang.reflect.Modifier;
  27. import java.lang.reflect.Type;
  28. import java.text.DateFormat;
  29. import java.text.SimpleDateFormat;
  30. import java.util.Date;
  31. import java.util.Iterator;
  32. import java.util.Map;
  33. import java.util.TimeZone;
  34. import java.util.Map.Entry;
  35. /**
  36. * Utility methods for using GSON
  37. *
  38. * @author Sachneet
  39. */
  40. public class GsonUtility {
  41. private static GsonBuilder gsonBuilder = new GsonBuilder();
  42. private static Gson gson;
  43. static {
  44. /* Register date serializer. */
  45. gsonBuilder.registerTypeAdapter(Date.class, new GsonUtility.DateAdapter());
  46. /* Use the custom serializer to serialize Map */
  47. gsonBuilder.registerTypeAdapter(Map.class, new GsonUtility.MapSerializer());
  48. gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT,
  49. Modifier.VOLATILE).setExclusionStrategies(new JdoExclusionStrategy())
  50. .create();
  51. }
  52. /*
  53. * Suppresses default constructor, ensuring no instance is created from
  54. * outside the class.
  55. */
  56. private GsonUtility() {
  57. }
  58. /**
  59. * This method serializes the specified object into its equivalent Json
  60. * representation.
  61. *
  62. * @param object the object to be converted to JSON string
  63. * @return the GSON string of the param object
  64. */
  65. public static String convertToJson(Object object) {
  66. String gsonString = null;
  67. gsonString = gson.toJson(object);
  68. return gsonString;
  69. }
  70. /**
  71. * This method deserializes the specified Json into an object of the
  72. * specified type
  73. *
  74. * @param <T> the type of the desired object
  75. * @param json the string from which the object is to be deserialized
  76. * @param classOfT the class of T
  77. * @return an object of type T from the string
  78. *
  79. */
  80. @SuppressWarnings("unchecked")
  81. public static <T> T convertFromJson(String json, Class<T> classOfT) {
  82. T target = (T) gson.fromJson(json, (Type) classOfT);
  83. return target;
  84. }
  85. /**
  86. * A date type adapter for a {@link Date} object.
  87. *
  88. * @author Charanjeet
  89. */
  90. private static class DateAdapter implements JsonSerializer<Date> {
  91. private final String pattern = "dd.MM.yyyy HH:mm:ss z";
  92. private final TimeZone indianTime = TimeZone.getTimeZone("IST");
  93. private final DateFormat format = new SimpleDateFormat(pattern);
  94. public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext
  95. context) {
  96. format.setTimeZone(indianTime);
  97. String dateFormatAsString = format.format(src);
  98. return new JsonPrimitive(dateFormatAsString);
  99. }
  100. }
  101. /**
  102. * A custom serializer for the {@link Map} class.
  103. *
  104. * @author Sachneet
  105. *
  106. */
  107. private static class MapSerializer implements JsonSerializer<Map<String, Object>> {
  108. @SuppressWarnings("unchecked")
  109. @Override
  110. public JsonElement serialize(Map<String, Object> src, Type typeOfSrc,
  111. JsonSerializationContext context) {
  112. /*
  113. * This JsonObject would be used to hold the same keys with their
  114. * values serialized
  115. */
  116. JsonObject map = new JsonObject();
  117. Iterator<?> iterator = src.entrySet().iterator();
  118. Map.Entry<String, Object> entry;
  119. Object value;
  120. JsonElement valueElementSerialized;
  121. /* Iterate the map and serialize the individual values */
  122. while (iterator.hasNext()) {
  123. entry = (Entry<String, Object>) iterator.next();
  124. value = entry.getValue();
  125. valueElementSerialized = context.serialize(value, value.getClass());
  126. /*
  127. * Put the serialized value into the JsonObject corresponding to
  128. * the respective key
  129. */
  130. map.add(entry.getKey().toString(), valueElementSerialized);
  131. }
  132. return map;
  133. }
  134. }
  135. /**
  136. * This class provides exclusion strategy to GSON builder.According to
  137. * ExclusionStrategy GSON builder decides whether to convert objects into
  138. * Json or not.
  139. *
  140. * @author gmaurya
  141. *
  142. */
  143. public static class JdoExclusionStrategy implements ExclusionStrategy {
  144. private static final String JDO = "jdo";
  145. @Override
  146. public boolean shouldSkipClass(Class<?> clazz) {
  147. return false;
  148. }
  149. @Override
  150. public boolean shouldSkipField(FieldAttributes f) {
  151. String fieldName = f.getName();
  152. /*
  153. * Skip fields that are used to save JDO state in detached objects
  154. */
  155. if (StringUtils.startsWith(fieldName, JDO)) {
  156. return true;
  157. }
  158. return false;
  159. }
  160. }
  161. }