/src/main/java/com/google/ie/common/util/GsonUtility.java
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 16package com.google.ie.common.util; 17 18import com.google.gson.ExclusionStrategy; 19import com.google.gson.FieldAttributes; 20import com.google.gson.Gson; 21import com.google.gson.GsonBuilder; 22import com.google.gson.JsonElement; 23import com.google.gson.JsonObject; 24import com.google.gson.JsonPrimitive; 25import com.google.gson.JsonSerializationContext; 26import com.google.gson.JsonSerializer; 27 28import org.apache.commons.lang.StringUtils; 29 30import java.lang.reflect.Modifier; 31import java.lang.reflect.Type; 32import java.text.DateFormat; 33import java.text.SimpleDateFormat; 34import java.util.Date; 35import java.util.Iterator; 36import java.util.Map; 37import java.util.TimeZone; 38import java.util.Map.Entry; 39 40/** 41 * Utility methods for using GSON 42 * 43 * @author Sachneet 44 */ 45public class GsonUtility { 46 private static GsonBuilder gsonBuilder = new GsonBuilder(); 47 private static Gson gson; 48 static { 49 /* Register date serializer. */ 50 gsonBuilder.registerTypeAdapter(Date.class, new GsonUtility.DateAdapter()); 51 /* Use the custom serializer to serialize Map */ 52 gsonBuilder.registerTypeAdapter(Map.class, new GsonUtility.MapSerializer()); 53 gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, 54 Modifier.VOLATILE).setExclusionStrategies(new JdoExclusionStrategy()) 55 .create(); 56 } 57 58 /* 59 * Suppresses default constructor, ensuring no instance is created from 60 * outside the class. 61 */ 62 private GsonUtility() { 63 64 } 65 66 /** 67 * This method serializes the specified object into its equivalent Json 68 * representation. 69 * 70 * @param object the object to be converted to JSON string 71 * @return the GSON string of the param object 72 */ 73 public static String convertToJson(Object object) { 74 String gsonString = null; 75 gsonString = gson.toJson(object); 76 return gsonString; 77 } 78 79 /** 80 * This method deserializes the specified Json into an object of the 81 * specified type 82 * 83 * @param <T> the type of the desired object 84 * @param json the string from which the object is to be deserialized 85 * @param classOfT the class of T 86 * @return an object of type T from the string 87 * 88 */ 89 @SuppressWarnings("unchecked") 90 public static <T> T convertFromJson(String json, Class<T> classOfT) { 91 T target = (T) gson.fromJson(json, (Type) classOfT); 92 return target; 93 } 94 95 /** 96 * A date type adapter for a {@link Date} object. 97 * 98 * @author Charanjeet 99 */ 100 private static class DateAdapter implements JsonSerializer<Date> { 101 102 private final String pattern = "dd.MM.yyyy HH:mm:ss z"; 103 private final TimeZone indianTime = TimeZone.getTimeZone("IST"); 104 private final DateFormat format = new SimpleDateFormat(pattern); 105 106 public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 107 context) { 108 109 format.setTimeZone(indianTime); 110 String dateFormatAsString = format.format(src); 111 return new JsonPrimitive(dateFormatAsString); 112 } 113 } 114 115 /** 116 * A custom serializer for the {@link Map} class. 117 * 118 * @author Sachneet 119 * 120 */ 121 private static class MapSerializer implements JsonSerializer<Map<String, Object>> { 122 123 @SuppressWarnings("unchecked") 124 @Override 125 public JsonElement serialize(Map<String, Object> src, Type typeOfSrc, 126 JsonSerializationContext context) { 127 /* 128 * This JsonObject would be used to hold the same keys with their 129 * values serialized 130 */ 131 JsonObject map = new JsonObject(); 132 Iterator<?> iterator = src.entrySet().iterator(); 133 Map.Entry<String, Object> entry; 134 Object value; 135 JsonElement valueElementSerialized; 136 /* Iterate the map and serialize the individual values */ 137 while (iterator.hasNext()) { 138 entry = (Entry<String, Object>) iterator.next(); 139 value = entry.getValue(); 140 valueElementSerialized = context.serialize(value, value.getClass()); 141 /* 142 * Put the serialized value into the JsonObject corresponding to 143 * the respective key 144 */ 145 map.add(entry.getKey().toString(), valueElementSerialized); 146 } 147 return map; 148 } 149 } 150 151 /** 152 * This class provides exclusion strategy to GSON builder.According to 153 * ExclusionStrategy GSON builder decides whether to convert objects into 154 * Json or not. 155 * 156 * @author gmaurya 157 * 158 */ 159 public static class JdoExclusionStrategy implements ExclusionStrategy { 160 161 private static final String JDO = "jdo"; 162 163 @Override 164 public boolean shouldSkipClass(Class<?> clazz) { 165 return false; 166 } 167 168 @Override 169 public boolean shouldSkipField(FieldAttributes f) { 170 String fieldName = f.getName(); 171 /* 172 * Skip fields that are used to save JDO state in detached objects 173 */ 174 if (StringUtils.startsWith(fieldName, JDO)) { 175 return true; 176 } 177 return false; 178 } 179 } 180} 181