gson 自定义对象转换格式

有时候我们希望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));
}

  

posted @ 2015-07-08 14:15  尼玛范爷  阅读(1469)  评论(0编辑  收藏  举报