我需要将某个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)

当前回答

我通过简单地更改POJO类的setter和getter方法的签名来解决这个问题。我所要做的就是更改getObject方法,以匹配映射器正在寻找的内容。在我的情况下,我原来有一个getImageUrl,但JSON数据有image_url,这是抛出映射器。我把setter和getter都改成了getImage_url和setImage_url。

其他回答

要么改变

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

to

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

----或----

将JSON字符串更改为

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

Java 11及更新版本的简单解决方案:

var mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .disable(FAIL_ON_UNKNOWN_PROPERTIES)
        .disable(WRITE_DATES_AS_TIMESTAMPS)
        .enable(ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);

重要的忽略是禁用'FAIL_ON_UNKNOWN_PROPERTIES'

进口com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties

对我来说,唯一的一条线

@JsonIgnoreProperties(ignoreUnknown = true)

也没起作用。

只需添加

@JsonInclude(Include.NON_EMPTY)

杰克逊测试盒框

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)