fis*_*che 23 java json gson java-8
我有一个日期时间属性的JSON,格式为"2014-03-10T18:46:40.000Z",我想使用Gson将其反序列化为java.time.LocalDateTime字段.
当我尝试反序列化时,我收到错误:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
Run Code Online (Sandbox Code Playgroud)
Ran*_*ula 21
当您反序列化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();
Run Code Online (Sandbox Code Playgroud)
Eve*_*ers 17
要扩展@Randula的答案,要将分区日期时间字符串(2014-03-10T18:46:40.000Z)解析为JSON:
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()).toLocalDateTime();
}
}).create();
Run Code Online (Sandbox Code Playgroud)
nte*_*rry 14
甚至进一步扩展@Evers答案:
您可以使用lambda进一步简化:
GSON GSON = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) ->
ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()).toLocalDateTime()).create();
Run Code Online (Sandbox Code Playgroud)
以下对我有用。
爪哇:
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); }
}).create();
Test test = gson.fromJson(stringJson, Test.class);
Run Code Online (Sandbox Code Playgroud)
其中stringJson是存储为 String 类型的 Json
杰森:
"dateField":"2020-01-30 15:00"
其中dateField是LocalDateTime类型,存在于 stringJson 字符串变量中。
| 归档时间: |
|
| 查看次数: |
20353 次 |
| 最近记录: |