gpt4 book ai didi

java - 反序列化对象时忽略嵌套的 json 字段

转载 作者:行者123 更新时间:2023-11-30 07:05:12 24 4
gpt4 key购买 nike

我正在尝试使用 JACKSON 反序列化此 JSON 字符串,

   [
{
"name": "United Kingdom",
"woeid": 23424975,
"placeType": {
"name": "Country",
"code": 12
}
}
]

我的类定义是

@JsonIgnoreProperties(ignoreUnknown = true)
public class Woeid {
private String name;
private Long woeid;

public Woeid() {
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getWoeid() {
return woeid;
}
public void setWoeid(Long woeid) {
this.woeid = woeid;
}
@Override
public String toString() {
return name;
}
}

我使用此代码进行反序列化

public List<Woeid> parse(String json) throws IOException {
jp = jsonFactory.createParser(json);
Woeid[] woeids= objectMapper.readValue(jp, Woeid[].class);
return Arrays.asList(woeids);
}

但是这个错误不断出现,只有当我从 json 字符串中删除“placeType”时它才起作用

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: [{"name": "United Kingdom","woeid": 23424975,"placeType": {"name": "Country","code": 12}}]; line: 1, column: 45]
(through reference chain: [Ljava.lang.Object[][0]->com.one.red.hashtagsdictionnary.model.Woeid["placeType"])

最佳答案

解决方案是添加这一行

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

关于java - 反序列化对象时忽略嵌套的 json 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261672/

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