10

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

Shubham Pandey
  • 1,498
  • 1
  • 15
  • 23
  • 1
    Possible duplicate of [Java 8 LocalDateTime deserialized using Gson](https://stackoverflow.com/questions/22310143/java-8-localdatetime-deserialized-using-gson) – AxelH Jul 05 '18 at 05:34
  • "_The error occurs when you are deserializing the LocalDate[Time] attribute because GSON fails to parse the value of the attribute as it's not aware of the LocalDate[Time] objects._" – AxelH Jul 05 '18 at 05:35

1 Answers1

14

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);
Shubham Pandey
  • 1,498
  • 1
  • 15
  • 23