gpt4 book ai didi

java - 使用 Gson 反序列化 LocalDateTime 不起作用

转载 作者:行者123 更新时间:2023-12-02 10:42:34 31 4
gpt4 key购买 nike

我需要使用 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]

最佳答案

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

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

关于java - 使用 Gson 反序列化 LocalDateTime 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824497/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com