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

当前回答

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)

其他回答

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

@JsonIgnoreProperties

它为我工作了以下代码:

ObjectMapper mapper =new ObjectMapper();    
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

使用Jackson 2.6.0,这对我来说是有效的:

private static final ObjectMapper objectMapper = 
    new ObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

并带有设置:

@JsonIgnoreProperties(ignoreUnknown = true)

谷歌带我来这里,我很惊讶地看到答案…所有人都建议绕过这个错误(这个错误在发展过程中总是会反咬4倍),而不是解决它,直到这位先生恢复了对SO的信心!

objectMapper.readValue(responseBody, TargetClass.class)

用于将json String转换为类对象,缺少的是TargetClass应该有公共getter / setter。OP的问题片段中也缺少相同的内容!:)

通过龙目岛,你的类如下应该工作!!

@Data
@Builder
public class TargetClass {
    private String a;
}

添加setter和getter解决了这个问题,我觉得实际的问题是如何解决它,而不是如何抑制/忽略错误。 我得到了错误“无法识别的领域..没有被标记为可忽略的…”

虽然我在类的顶部使用了下面的注释,但它无法解析json对象并给我输入

@JsonIgnoreProperties(ignoreUnknown = true)

然后我意识到我没有添加setter和getter,在添加setter和getter到“包装器”和“学生”后,它就像一个魅力。