我有带有“2014-03-10T18:46:40.000Z”格式的日期时间属性的 JSON,我想使用 Gson 将其反序列化为 java.time.LocalDateTime 字段。
当我尝试反序列化时,出现错误:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
当您反序列化 LocalDateTime 属性时,会发生错误,因为 GSON 无法解析该属性的值,因为它不知道 LocalDateTime 对象。
使用 GsonBuilder 的 registerTypeAdapter 方法定义自定义 LocalDateTime 适配器。
以下代码片段将帮助您反序列化 LocalDateTime 属性。
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)