Created
September 16, 2014 01:49
-
-
Save yamingd/99bcace7910614e59297 to your computer and use it in GitHub Desktop.
GsonUtil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.*; | |
import java.lang.reflect.Type; | |
import java.util.Date; | |
/** | |
* Created by yaming_deng on 14-9-15. | |
*/ | |
public class GsonUtil { | |
private static Gson gson = null; | |
static { | |
GsonBuilder builder = new GsonBuilder(); | |
//builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); | |
builder.registerTypeAdapter(Date.class, new DateDeserializer()); | |
builder.registerTypeAdapter(Date.class, new DateSerializer()); | |
gson = builder.create(); | |
} | |
public static class DateDeserializer implements JsonDeserializer<Date>{ | |
@Override | |
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { | |
return new Date(json.getAsLong()); | |
} | |
} | |
public static class DateSerializer implements JsonSerializer<Date>{ | |
@Override | |
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { | |
return new JsonPrimitive(src.getTime()); | |
} | |
} | |
public static String toJson(Object o){ | |
return gson.toJson(o); | |
} | |
public static <T> T asT(Class<T> clazz, String json){ | |
return gson.fromJson(json, clazz); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment