杰森搞砸了分钟价值 [英] Gson mess up with minute value
问题描述
我正在使用gson将序列化的消息转换为对象,但是将一个属性转换为java.sql.Timestamp
I am using gson to convert serialized message to object, but I have problem with converting one attribute to java.sql.Timestamp
JSON中的开始时间属性为
The start time attribute in JSON is
{...other_fields, "start_time": "2020-05-27 05:23:43.022610"}
我的Gson解析器以这种方式初始化
And my Gson parser is initialized this way
new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss.S").create();
对象已正确解析,但是开始时间应具有不同的分钟和秒值.解析开始时间的结果是:2020-05-27 05:24:05.61
The object is parsed properly, but the start time has different minutes and seconds values as it should. The result of parse start time is: 2020-05-27 05:24:05.61
我想念什么?
编辑1 :
Java版本:
1.8
Gson版本:2.8.2
Java Version:
1.8
Gson version:2.8.2
Edit2 :
将格式更改为
yyyy-MM-dd HH:mm:ss
之后(省略 毫秒),我得到了正确的结果,但没有毫秒值. 我可以接受,但是如果有人仍然可以 解释这个问题.
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.
推荐答案
SimpleDateFormat
不会在解析过程中不支持微秒. S
表示毫秒,表示小数点后仅3位.
And SimpleDateFormat
doesn't support microseconds during parsing. S
denotes miliseconds, which means only 3 places after the decimal.
这可以证明.在您的JSON中删除微秒,并使用2020-05-27 05:23:43.022
作为输入.
This can be proved. In your JSON remove microseconds and use 2020-05-27 05:23:43.022
as input.
输出应为
2020-05-27 05:23:43.022
2020-05-27 05:23:43.022
Timestamp
确实支持微秒,如果要将2020-05-27 05:23:43.022610
(以微秒为单位)转换为Timestamp
,最好编写
Timestamp
does support microseconds and if you want to convert 2020-05-27 05:23:43.022610
(with microseconds) to Timestamp
, you are better off writing a 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();
这篇关于杰森搞砸了分钟价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!