具有嵌套类型属性的杰克逊多态反序列化

时间:2019-04-26 18:47:54

标签: java jackson polymorphism

我的目标是根据属性下的类型字段将以下json反序列化为正确的子类:

{
  "totalSize": 1,
  "done": true,
  "records": [
    {
      "attributes": {
        "type": "Custom_Object__c",
        "url": "\/services\/data\/v44.0\/sobjects\/Custom_Object__c\/a00Y000000fM1CzUFZ"
      },
      "Name": "Name Test",
      "Price_Out__c": false,
      "Description__c": "This is a sample description!",
      "Ticket_Number__c": "AM-12345"
    }
  ]
}

我的顶级类是QueryResult.java:

public class QueryResult {
    private String totalSize;
    private Boolean done;

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
    @JsonSubTypes(value = {
            @JsonSubTypes.Type(value = Custom_Object__c.class, name = "Custom_Object__c")
    })
    private List<Records> records = new ArrayList<>();

    public String getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(String totalSize) {
        this.totalSize = totalSize;
    }

    public Boolean getDone() {
        return done;
    }

    public void setDone(Boolean done) {
        this.done = done;
    }

    public List<Records> getRecords() {
        return records;
    }

    public void setRecords(List<Records> records) {
        this.records = records;
    }
}

Records.java:

public abstract class Records {
    private Attributes attributes;

    public Attributes getAttributes() {
        return attributes;
    }

    public void setAttributes(Attributes attributes) {
        this.attributes = attributes;
    }
}

CustomObject.java:

public class ManagedOrg extends Records {
    private String Name;
    private String Price_Out__c;
    private String Description__c;
    private String Ticket_Number__c;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getPrice_Out__c() {
        return Price_Out__c;
    }

    public void setPrice_Out__c(String price_Out__c) {
        Price_Out__c = price_Out__c;
    }

    public String getDescription__c() {
        return Description__c;
    }

    public void setDescription__c(String description__c) {
        Description__c = description__c;
    }

    public String getTicket_Number__c() {
        return Ticket_Number__c;
    }

    public void setTicket_Number__c(String ticket_Number__c) {
        ticket_Number__c = Ticket_Number__c;
    }
}

我无法使它正常工作。标识属性嵌套在“记录”列表中:

"records": [
{
  "attributes": {
    "type": "Custom_Object__c",

有可能让杰克逊使用该值作为JsonTypeId?我以为上面的注释可以解决这个问题,但是我收到一条错误消息,说我缺少Records类的属性“ type”。那是因为type属性在Records类本身内吗?

0 个答案:

没有答案