有时候我们希望gson按照我们想要的方式转换,比如将日期转换为时间戳
class GsonBuilderUtil { public static Gson create() {
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
Gson gson = gb.create();
return gson;
}
} class DateSerializer implements JsonSerializer<Date> {
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
} public static void main(String[] args) {
Gson gson = GsonBuilderUtil.create();
Map map = new HashedMap();
map.put("aaa",new Date());
System.out.println(gson.toJson(map));
}