json - Java 8 LocalDateTime deserialized using Gson -
i have jsons date-time attribute in format "2014-03-10t18:46:40.000z", want deserialize java.time.localdatetime field using gson.
when tried deserialize, error:
java.lang.illegalstateexception: expected begin_object string
the error occurs when deserializing localdatetime attribute because gson fails parse value of attribute it's not aware of localdatetime objects.
use gsonbuilder's registertypeadapter method define custom localdatetime adapter. following code snippet deserialize 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();
Comments
Post a Comment