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

当前回答

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

其他回答

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

@JsonIgnoreProperties

为了防止其他人像我一样使用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的旧版本。

没有setter/getter的最短解决方案是将@JsonProperty添加到类字段:

public class Wrapper {
    @JsonProperty
    private List<Student> wrapper;
}

public class Student {
    @JsonProperty
    private String name;
    @JsonProperty
    private String id;
}

此外,您在json中称学生列表为“wrapper”,因此Jackson希望类具有一个名为“wrapper”的字段。

要么改变

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

to

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

----或----

将JSON字符串更改为

{"students":[{"id":"13","name":"Fred"}]}

我也遇到了类似的问题,唯一的区别是我正在使用YAML文件而不是JSON文件。所以我在创建ObjectMapper时使用YamlFactory()。另外,我的Java POJO的属性是私有的。 然而,所有这些答案中提到的解决方案都没有帮助。我的意思是,它停止抛出错误并开始返回Java对象但Java对象的属性将为null。

我只是做了以下几点:-

objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

而不需要:-

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

现在,我能够反序列化数据从Yaml文件到Java对象。所有属性现在都不是空的。这种解决方案也适用于JSON方法。