有些特定需求, 比如说搜索引擎, 很多人都要求时间必须是时间戳. 所以, 我们把时间转成最原始的Long型. Gson默认的是不支持的, 需要手动处理一下.
日期转Long
代码语言:javascript复制public class DateSerializer implements JsonSerializer<Date> {
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}
Long转日期
代码语言:javascript复制public class DateDeserializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}
}
构造通用工具类
代码语言:javascript复制public class GsonUtils {
private static Gson instance = null;
public synchronized static Gson getGson(){
if(instance == null) {
GsonBuilder builder = new GsonBuilder();
builder.addSerializationExclusionStrategy(new IgnoreStrategy());
builder.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
builder.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
instance = builder.create();
}
return instance;
}
}