在Gson中反序列化LocalDateTime无效

时间:2018-10-15 20:43:00

标签: java json serialization gson

我需要使用Gson将字符串转换为对象:

gson.fromJson("{\"message\":\"any msg.\",\"individual\":{\"id\":100,\"citizenshipList\":[{\"date\":[2018,10,15,16,29,36,402000000]}]}}", Response.class)

其中

public class Response {
    private String message;
    private Individual individual;
}

public class Individual {
 private Integer id;
 private List<Citizenship> citizenshipList = new ArrayList<>();
}

public class Citizenship {

  @DateTimeFormat(pattern="d::MMM::uuuu HH::mm::ss")
  LocalDateTime date;

}

我遇到此错误

  

java.lang.IllegalStateException:应该为BEGIN_OBJECT,但是   BEGIN_ARRAY在第1行第122列的路径   $ .individual.citizenshipList [0] .date

我也尝试过修改Gson:

Gson gson1 = 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();

但这给了我这个错误:

  

java.lang.IllegalStateException:不是JSON对象:   [2018,10,15,16,29,36,402000000]

1 个答案:

答案 0 :(得分:1)

您发布的两个错误都说明了问题所在:

  

不是JSON对象:[2018,10,15,16,29,36,402000000]

     

预期为BEGIN_OBJECT,但为BEGIN_ARRAY

[2018,10,15,16,29,36,402000000]是一个JSON 数组,GSON需要一个JSON object ,例如:{}

一种解决方法是将JsonDeserializer改为使用JsonArray而不是JsonObject

Gson gson1 = new GsonBuilder()
            .registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
                @Override
                public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                    JsonArray array = json.getJSONArray("date");
                    return LocalDateTime.of(
                                            // Set all values here from
                                            // `array` variable
                                            );
                }
            }).create();