Deserialize date attribute of json into LocalDate

可紊 提交于 2020-04-29 12:50:51

问题


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.

For json input :

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

I am getting error for startDate and endDate :

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING


回答1:


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();

and then

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


来源:https://stackoverflow.com/questions/51183967/deserialize-date-attribute-of-json-into-localdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!