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

Ignore a nested json field when deserializing object

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

1
2
3
4
5
6
7
8
9
10
   [
    {
       "name":"United Kingdom",
       "woeid": 23424975,
       "placeType": {
                       "name":"Country",
                       "code": 12
                    }
     }
   ]

我的班级定义是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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;
    }
}

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

1
2
3
4
5
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"时它才有用

1
2
3
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"])


解决方案是添加此行

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