Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDateTime deserialized using Gson

I have JSONs with a date-time attribute in the format "2014-03-10T18:46:40.000Z", which I want to deserialize into a java.time.LocalDateTime field using Gson.

When I tried to deserialize, I get the error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING 
like image 357
fische Avatar asked Mar 10 '14 20:03

fische


1 Answers

The error occurs when you are deserializing the LocalDateTime attribute because GSON fails to parse the value of the attribute as it's not aware of the LocalDateTime objects.

Use GsonBuilder's registerTypeAdapter method to define the custom LocalDateTime adapter. Following code snippet will help you to deserialize the LocalDateTime attribute.

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(); 
like image 95
Randula Avatar answered Sep 20 '22 14:09

Randula