当前位置: 移动技术网 > IT编程>开发语言>Java > gson反序列化localdateTime格式化

gson反序列化localdateTime格式化

2020年08月17日  | 移动技术网IT编程  | 我要评论
如果需要反序列化内容是 "yyyy-MM-dd HH:mm:ss"格式那么使用网上搜出来的Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer() {@Overridepublic LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializ

如果需要反序列化内容是 "yyyy-MM-dd HH:mm:ss"格式
那么使用网上搜出来的
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
}).create();
会报错转化错误。
大概是因为json.getAsJsonPrimitive().getAsLong()无法转为long。
需要做出一点修改
.registerTypeAdapter(LocalDateTime.class, new JsonDeserializer() {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(),DateTimeFormatter.ofPattern( “yyyy-MM-dd HH:mm:ss”));
}
})

就可以了。

另外:我在dubbo+springboot使用过程中retrun对象中有LocalDateTime会报堆栈溢出错误。目前转为date类型,待续。

有错误请指教!

本文地址:https://blog.csdn.net/gdssgxf/article/details/108025217

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网