有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jackson无法识别存在的字段

这是我的JSON

{"totalSize":46,"done":true,"records":[{"Name":"Wamu I","Start_Date__c":"2016-09-26T16:56:10.000+0000","Status__c":"Completed","Type__c":"Your were expecting success, but In reality it was I, Dio!!!"}]}

下面是我的两个实体类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class EsidesiJobEntity {

    @JsonProperty("totalSize")
    private @Getter @Setter Integer totalSize;

    @JsonProperty("done")
    private @Getter @Setter Boolean isDone;

    @JsonProperty("records")
    private @Getter @Setter List<KarsEntity> records;

    @Override
    @JsonIgnore
    public String toString(){

        List<String> recordsObjectString = new ArrayList<String>();

        this.records.forEach((record) -> 
        {
            recordsObjectString.add(record.toString());
        });
        return "{ totalSize:"+this.totalSize+", isDone:"+this.isDone+", records:["+recordsObjectString.toString()+"]";
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
public class KarsEntity {

    @JsonProperty("Name")
    private @Getter @Setter String name;

    @JsonProperty("Start_Date__c")
    private @Getter @Setter String startDate;

    @JsonProperty("Status__c")
    private @Getter @Setter String status;

    @Override
    public String toString(){
        return "{ name:"+this.name+", startDate:"+this.startDate+", status:"+this.status+"}";
    }
}

出于某种原因,当我将该json字符串映射到EsidesJobEntity时,会出现以下错误:

Unrecognized field "totalSize"

但它肯定存在于JSON和实体中

下面是我编写的代码,用于将字符串映射到实体以供参考:

EsidesiEntity apexJobResponseEntity;

ObjectMapper apexMapper = new ObjectMapper();
try {
    apexJobResponseEntity = apexMapper.readValue(apexResponseString, EsidesiEntity.class);
} ...

我是不是错过了一些基本的东西

(顺便说一句,如果类/实体名称中存在一些不一致,那是因为我在将它们发布到网上之前对它们进行了重命名。请告诉我,我会在看到它们时修复它们。)

谢谢


共 (1) 个答案

  1. # 1 楼答案

    您正在使用Lombok。Jackson看不到你的getter和setter方法

    所以你有两个选择:

    1. 不要使用Lombok并实现getter和setter方法
    2. 将Lombok与此附加库一起使用:jackson-lombok

    如果您使用的是maven,那么将jackson lombok添加到您的pom中。xml:

    <dependency>
        <groupId>com.xebia</groupId>
        <artifactId>jackson-lombok</artifactId>
        <version>1.1</version>
    </dependency>
    

    然后用以下方式配置ObjectMapper

    ObjectMapper apexMapper = new ObjectMapper();
    apexMapper.setAnnotationIntrospector(new JacksonLombokAnnotationIntrospector());
    [...]