我需要将某个JSON字符串转换为Java对象。我正在使用Jackson进行JSON处理。我无法控制输入JSON(我从web服务读取)。这是我的输入JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

下面是一个简化的用例:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

我的实体类是:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

我的Wrapper类基本上是一个容器对象来获取我的学生列表:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

我一直得到这个错误和“包装器”返回null。我不知道少了什么。有人能帮帮我吗?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

当前回答

由于json属性和java属性的名称不匹配,请将student字段注释如下

public Class Wrapper {
    @JsonProperty("wrapper")
    private List<Student> students;
    //getters & setters here
}

其他回答

你可以使用

ObjectMapper objectMapper = getObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

它将忽略所有未声明的属性。

在我的情况下,错误是由于以下原因

最初它工作得很好,然后我重命名了一个变量,使 代码的变化,它给了我这个错误。 然后我申请杰克逊无知财产也,但它没有工作。 最后,在重新定义我的getter和setter方法根据 我的变量名称此错误已解决

所以一定要重定义getter和setter。

我曾经遇到过这种情况,当时我的JSON有效负载包括一个API无法识别的属性。解决方案是重命名/删除违规属性。

FAIL_ON_UNKNOWN_PROPERTIES选项默认为true:

FAIL_ON_UNKNOWN_PROPERTIES (default: true)
Used to control whether encountering of unknown properties (one for which there is no setter; and there is no fallback "any setter" method defined using @JsonAnySetter annotation) should result in a JsonMappingException (when enabled), or just quietly ignored (when disabled)

这可能是一个非常晚的响应,但只是将POJO更改为这个应该解决问题中提供的json字符串(因为,输入字符串不像你说的那样在你的控制范围内):

public class Wrapper {
    private List<Student> wrapper;
    //getters & setters here
}