使类结构如下所示
class item {
String link;
}
@JsonIgnoreProperties(ignoreUnknown=true)
class Result {
item[] items;
}
@JsonIgnoreProperties(ignoreUnknown=true) 如果 JSON 字符串中有任何属性但不在你的类中,那么解析器将不会通过任何异常,它只会忽略它。
编辑:带有示例的完整代码
class Item {
String link;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Result {
List<Item> items;
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
public class JsonCommonTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String data = "{\"items\": [{\"link\": \"address1\"},{\"link\": \"address2 \"}]}";
Result result = mapper.readValue(data, Result.class);
System.out.println(result.items.size());
}
}