简体   繁体   中英

Java 8 LocalDateTime Deserialization using gson

I want to deserialize a json String containing LocalDateTime fields in to a class using gson.

But this throws nullpointer exceptions.

My JSON:

metrics": {
"measurements": [
{
"serviceName": "myService",
"start": {
"year": 2018,
"month": "APRIL",
"dayOfMonth": 26,
"dayOfWeek": "THURSDAY",
"dayOfYear": 116,
"monthValue": 4,
"hour": 18,
"minute": 53,
"second": 51,
"nano": 243000000,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
},
"stop": {
"year": 2018,
"month": "APRIL",
"dayOfMonth": 26,
"dayOfWeek": "THURSDAY",
"dayOfYear": 116,
"monthValue": 4,
"hour": 18,
"minute": 53,
"second": 51,
"nano": 841000000,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
},
"processingTime": 598
}

The code i use to get my object:

Metrics metrics = gson.fromJson(jsonString, Metrics.class);

But gson is only able to deserialize the processingTime field of my object.

I've tried this too:

Java 8 LocalDateTime deserialized using Gson

but this results in

Caused by: java.lang.IllegalStateException: This is not a JSON Primitive.
    at com.google.gson.JsonElement.getAsJsonPrimitive(JsonElement.java:122)
    at com.foo.config.AppConfig.lambda$gson$1(AppConfig.java:63)

any thoughts?

Thanks

I was able to resolve it myself by helping the LocalDateTime type adapter:

   @Bean
    public Gson gson() {
        return new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
                    @Override
                    public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                        JsonObject jo = json.getAsJsonObject();
                        return LocalDateTime.of(jo.get("year").getAsInt(),
                                jo.get("monthValue").getAsInt(),
                                jo.get("dayOfMonth").getAsInt(),
                                jo.get("hour").getAsInt(),
                                jo.get("minute").getAsInt(),
                                jo.get("second").getAsInt(),
                                jo.get("nano").getAsInt());
                    }
                }).create();

Incase you're having this same issue but you're also expecting date in string format (eg 2019-11-18 ) You can use use a try catch block as so:

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 {
        try {
            return LocalDate.parse(json.getAsJsonPrimitive().getAsString());
        } catch (IllegalStateException e) {
            JsonObject jo = json.getAsJsonObject();
            return LocalDate.of(jo.get("year").getAsInt(), jo.get("monthValue").getAsInt(), jo.get("dayOfMonth").getAsInt());
        }
    }
}).create();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM