将json的date属性反序列化为LocalDate [英] Deserialize date attribute of json into LocalDate

查看:196
本文介绍了将json的date属性反序列化为LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Gson反序列化格式为 2018-05-27的json中的date属性。我希望日期在反序列化后为LocalDate格式。

I am trying to de-serialize date attribute in json of format "2018-05-27" using Gson. I want date to be in LocalDate format after de-serialization.

对于json输入:

{
id:1,1,
name: test,
startDate: 2018-01-01,
endDate: 2018-01-05 ,
}

{ "id" : 1, "name" : "test", "startDate" : "2018-01-01", "endDate" : "2018-01-05", }

startDate和endDate出现错误:

I am getting error for startDate and endDate :

java.lang。 IllegalStateException:预期为BEGIN_OBJECT,但为STRING

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

推荐答案

我们做到这一点的方法是:

The way we can do this is :

private static final Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new JsonDeserializer<LocalDate>() {
            @Override
            public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                return LocalDate.parse(json.getAsJsonPrimitive().getAsString());
            }
        }).create();

然后

YourClassName yourClassObject = gson.fromJson(msg, YourClassName.class);

这篇关于将json的date属性反序列化为LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆