我有一个日期时间属性的JSON,格式为“2014-03-10T18:46:40.000Z”,我想使用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();