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

时间:2016-10-26 11:57:31

标签: java json jackson

我正在尝试使用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"])

1 个答案:

答案 0 :(得分:1)

解决方案是添加此行

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