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

当前回答

如果你想将@JsonIgnoreProperties应用到应用程序中的所有类,那么最好的方法是重写Spring引导默认jackson对象。

在您的应用程序配置文件中定义一个bean来创建这样的杰克逊对象映射器。

@Bean
    public ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

现在,您不需要标记每个类,它将忽略所有未知属性。

其他回答

我已经尝试了下面的方法,它适用于这样的JSON格式读取杰克逊。 使用已经建议的解决方案:用@JsonProperty("wrapper")注释getter

你的包装类

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

我对包装类的建议

public Class Wrapper{ 

  private StudentHelper students; 

  //getters & setters here 
  // Annotate getter
  @JsonProperty("wrapper")
  StudentHelper getStudents() {
    return students;
  }  
} 


public class StudentHelper {

  @JsonProperty("Student")
  public List<Student> students; 

  //CTOR, getters and setters
  //NOTE: If students is private annotate getter with the annotation @JsonProperty("Student")
}

然而,这将为您提供格式的输出:

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

更多信息请访问https://github.com/FasterXML/jackson-annotations

Jackson正在抱怨,因为它无法在类Wrapper中找到一个名为“Wrapper”的字段。它这样做是因为JSON对象有一个名为“包装器”的属性。

我认为解决办法是将Wrapper类的字段重命名为“Wrapper”而不是“students”。

不知怎的,10年过去了,45篇帖子之后,还没有人对我的情况给出正确答案。

@Data //Lombok
public class MyClass {
    private int foo;
    private int bar;

    @JsonIgnore
    public int getFoobar() {
      return foo + bar;
    }
}

在我的例子中,我们有一个名为getFoobar()的方法,但没有foobar属性(因为它是从其他属性计算的)。类上的@JsonIgnoreProperties不起作用。

解决方案是用@JsonIgnore注释方法

问题是你的属性在你的JSON被称为“包装”和你的属性在wrapper .class被称为“学生”。

所以要么…

更正类或JSON中的属性名称。 根据StaxMan的注释注释您的属性变量。 注释setter(如果有的话)

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

@JsonIgnoreProperties