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

当前回答

你只需将List的字段从“students”更改为“wrapper”,只是json文件,mapper就会查找它。

其他回答

将Wrapper类更改为

public Class Wrapper {

          @JsonProperty("wrapper")  // add this line
          private List<Student> students;
}

这样做的目的是将students字段识别为json对象的包装键。

此外,我个人更喜欢使用Lombok注解的getter和setter作为

@Getter
@Setter
public Class Wrapper {

          @JsonProperty("wrapper")  // add this line
          private List<Student> students;
}

因为我没有同时用Lombok和@JsonProperty测试上面的代码,所以我建议您也将下面的代码添加到Wrapper类中,以覆盖Lombok的默认getter和setter。

public List<Student> getWrapper(){
     return students;
}

public void setWrapper(List<Student> students){
     this.students = students;
}

还可以使用Jackson来反序列化列表。

这个解决方案在读取json流时是通用的,只需要获取一些字段,而在域类中没有正确映射的字段可以忽略:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)

一个详细的解决方案是使用jsonschema2pojo等工具来自动生成所需的域类,例如从json响应的Schema中生成Student。您可以通过任何在线json到模式转换器来实现后者。

在我的例子中,它很简单:更新了rest -服务JSON对象(添加了一个属性),但没有更新rest -客户端JSON对象。只要我已经更新了JSON客户端对象的“不可识别的字段…’这个例外已经消失了。

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

objectMapper.readValue(responseBody, TargetClass.class)

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

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

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

您的json字符串没有与映射的类内联。 更改输入字符串

String jsonStr = "{\"students\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";

或者更改映射的类

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