【问题标题】:How to serialize Date to long using gson?如何使用 gson 将日期序列化为长?
【发布时间】:2017-06-18 03:49:06
【问题描述】:

我最近将我们的一些序列化从Jackson 切换到Gson。发现 Jackson 将日期序列化为 long。

但是,Gson 默认将日期序列化为字符串。

使用 Gson 时如何将日期序列化为长整数?谢谢。

【问题讨论】:

    标签: java json date jackson gson


    【解决方案1】:

    第一种类型的适配器进行反序列化,第二种类型的适配器进行序列化。

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
            .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
            .create();
    

    用法:

    String jsonString = gson.toJson(objectWithDate1);
    ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
    assert objectWithDate1.equals(objectWithDate2);
    

    【讨论】:

    【解决方案2】:

    你可以用一种类型的适配器做两个方向:

    public class DateLongFormatTypeAdapter extends TypeAdapter<Date> {
    
        @Override
        public void write(JsonWriter out, Date value) throws IOException {
            if(value != null) out.value(value.getTime());
            else out.nullValue();
        }
    
        @Override
        public Date read(JsonReader in) throws IOException {
            return new Date(in.nextLong());
        }
    
    }
    

    Gson 构建器:

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
            .create();
    

    【讨论】:

    • 不错。尤其是单一类型。 nextLong() 有点含蓄:( 赞成。
    • 谢谢。实际上我们期望很长,那只是gson提供的转换快捷方式,所以我看不出有什么问题。文档:“返回下一个标记的长值,使用它。如果下一个标记是字符串,则此方法将尝试将其解析为长整数。如果下一个标记的数值不能由 Java 长整数精确表示,则此方法抛出。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多