使用Gson转json字符串序列化问题
gson序列化会遇到问题:
java.lang.UnsupportedOperationException: Expecting parameterized type, got class
Are you missing the use of TypeToken idiom?
See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener
at com.google.gson.TypeInfoFactory.getActualType(TypeInfoFactory.java:105)
at com.google.gson.TypeInfoFactory.getTypeInfoForField(TypeInfoFactory.java:54)
at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:156)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:131)
at com.google.gson.JsonSerializationContextDefault.serialize(JsonSerializationContextDefault.java:56)
at com.google.gson.Gson.toJsonTree(Gson.java:233)
at com.google.gson.Gson.toJson(Gson.java:273)
at com.google.gson.Gson.toJson(Gson.java:253)
解决办法如下:
private static Gson gsonUtils = null;
public synchronized static Gson getGsonUtils(){
if(gsonUtils == null) {
GsonBuilder builder = new GsonBuilder()
.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}).registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
}).setDateFormat(DateFormat.LONG);
gsonUtils = builder.create();
}
return gsonUtils;
}