杰克逊没有识别存在的字段

时间:2016-09-29 20:15:06

标签: java json 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字符串映射到EsidesiJobEntity时,我收到以下错误:

Unrecognized field "totalSize"

但它完全同时存在于JSON和实体中!

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

EsidesiEntity apexJobResponseEntity;

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

我错过了一些非常基本的东西吗?

(顺便说一句,如果类/实体名称有些不一致,那是因为我在将它们发布到网上之前将其重命名。让我知道,我会在看到它们时修复它们。)

谢谢!

1 个答案:

答案 0 :(得分:1)

您正在使用Lombok。杰克逊无法看到你的吸气剂和制定者的方法。

所以你有两个选择:

  1. 不要使用Lombok并实现getter和setter方法
  2. 将Lombok与此附加库一起使用:jackson-lombok
  3. 如果你正在使用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());
    [...]