Gson 弄乱了微小的价值

Gson mess up with minute value

我正在使用 gson 将序列化消息转换为对象,但我在将一个属性转换为 java.sql.Timestamp

时遇到问题

JSON中的开始时间属性是

{...other_fields, "start_time": "2020-05-27 05:23:43.022610"}

我的 Gson 解析器就是这样初始化的

new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss.S").create();

对象已正确解析,但开始时间具有不同的分钟和秒值。解析开始时间的结果是:2020-05-27 05:24:05.61

我错过了什么?

编辑 1:

Java Version: 1.8
Gson version: 2.8.2

编辑2

After change format to yyyy-MM-dd HH:mm:ss (omitting milliseconds) I got the right result, but without milliseconds value. I can live with that, but it would be nice if someone could still explain this issue.

GsonBuilder.setDateFormat() 使用 SimpleDateFormat.

并且SimpleDateFormat在解析期间不支持微秒。 S表示毫秒,也就是小数点后只有3位。

这是可以证明的。在您的 JSON 中删除微秒并使用 2020-05-27 05:23:43.022 作为输入。

输出将是

2020-05-27 05:23:43.022

Timestamp 确实支持微秒,如果你想将 2020-05-27 05:23:43.022610(带微秒)转换为 Timestamp,你最好写一个 custom GSON deserializer

编辑:时间戳

的示例反序列化器
class TimestampDeserializer implements JsonDeserializer<Timestamp> {

    @Override
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        // Handle null checks or format check, etc.
        return Timestamp.valueOf(json.getAsString());
    }
}

用法:

Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(Timestamp.class, new TimestampDeserializer()).create();