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

  

相关文章:

  • 2021-11-22
  • 2021-11-09
  • 2021-08-13
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
猜你喜欢
  • 2022-12-23
  • 2021-08-10
  • 2021-05-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-05
相关资源
相似解决方案