Java 在Gson中反序列化LocalDateTime不起作用

Java 在Gson中反序列化LocalDateTime不起作用,java,json,serialization,gson,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 Individu

我需要使用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\u对象,但为 从第1行第122列路径开始\u数组 $.individual.citizenshipList[0]。日期

我还尝试了一种改进的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,36402000000]


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

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

应为BEGIN\u对象,但为BEGIN\u数组

[2018,10,15,16,29,3640200000]是一个JSON数组,GSON需要一个JSON对象,例如:{}

解决此问题的一种方法是修改JsonDeserializer以使用JsonArray而不是JsonObject:


为什么将日期拆分为数组?而不是作为2018-10-15传递…?尝试使用JsonArray而不是JsonObject。我不是这么做的,这是带有MockHttpServletResponse的Mockito mvc。getContentAsString和属性使用LocalDateTimeThank,是的,就是这样。。但更一般的原因是,在我的单元中,mockito使用Jackson序列化对象,Jackson使用jsonarray序列化对象
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();