有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Gson中的java反序列化LocalDateTime不起作用

我需要使用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: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 122 path $.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: Not a JSON Object: [2018,10,15,16,29,36,402000000]


共 (1) 个答案

  1. # 1 楼答案

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

    Not a JSON Object: [2018,10,15,16,29,36,402000000]

    Expected BEGIN_OBJECT but was BEGIN_ARRAY

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

    解决此问题的一种方法是修改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();