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

当前回答

将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来反序列化列表。

其他回答

在我的情况下,我必须添加公共getter和setter,以使字段私有。

ObjectMapper mapper = new ObjectMapper();
Application application = mapper.readValue(input, Application.class);

我使用jackson-databind 2.10.0。pr3。

在我的情况下,错误是由于以下原因

最初它工作得很好,然后我重命名了一个变量,使 代码的变化,它给了我这个错误。 然后我申请杰克逊无知财产也,但它没有工作。 最后,在重新定义我的getter和setter方法根据 我的变量名称此错误已解决

所以一定要重定义getter和setter。

Json:

 "blog_host_url": "some.site.com"

科特林字段

var blogHostUrl: String = "https://google.com"

在我的情况下,我只需要使用@JsonProperty注释在我的数据类。

例子:

data class DataBlogModel(
       @JsonProperty("blog_host_url") var blogHostUrl: String = "https://google.com"
    )

这是文章:https://www.baeldung.com/jackson-name-of-property

第一个答案几乎是正确的,但需要的是改变getter方法,不是字段——字段是私有的(不自动检测);此外,如果字段和getter都是可见的,则getter的优先级高于字段。(也有一些方法可以让私有字段可见,但如果你想要getter,那就没什么意义了)

所以getter应该被命名为getWrapper(),或者用以下注解:

@JsonProperty("wrapper")

如果你喜欢getter方法名。

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

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

@JsonIgnoreProperties(ignoreUnknown = true)

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