Java 8 LocalDateTime使用gson进行反序列化

时间:2018-04-26 17:34:23

标签: java json gson

我想使用gson将包含LocalDateTime字段的json String反序列化为类。

但是这会引发nullpointer异常。

我的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
}

我用来获取对象的代码:

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

但是gson只能反序列化我对象的processingTime字段。

我也试过这个:

Java 8 LocalDateTime deserialized using Gson

但这会导致

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)

任何想法?

由于

1 个答案:

答案 0 :(得分:0)

我能够通过帮助LocalDateTime类型适配器来解决它:

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