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

当前回答

为了防止其他人像我一样使用force-rest-api,下面是我如何使用这个讨论来解决它(Kotlin):

var result = forceApi.getSObject("Account", "idhere")
result.jsonMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,  false)
val account: Account = result.`as`(Account::class.java)

看起来force-rest-api使用的是jackson的旧版本。

其他回答

您需要验证正在解析的类的所有字段,使其与原始JSONObject中的字段相同。它帮助了我,对我来说。

@JsonIgnoreProperties(ignoreUnknown = true)根本没有帮助。

不知怎的,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(如果有的话)

POJO应该定义为

响应类

public class Response {
    private List<Wrapper> wrappers;
    // getter and setter
}

包装器类

public class Wrapper {
    private String id;
    private String name;
    // getters and setters
}

和mapper来读取值

Response response = mapper.readValue(jsonStr , Response.class);

另一种可能是application.properties中的这个属性 Spring.jackson.deserialization.fail-on-unknown-properties =false,它不需要在应用程序中更改任何其他代码。当你认为合同是稳定的,你可以删除这个属性或标记它为真。