另一种选择是使用Jongo将多态处理委托给Jackson。我写了一篇包含一些示例的博客文章,您可以在GitHub 上找到完整的代码库。
在您的特定场景中,您使用 Jackson 的解决方案将如下所示:
public enum DocTypeEnum {
INVOICE(Constants.INVOICE), ORDER(Constants.ORDER);
DocTypeEnum(String docTypeString) {
}
public static class Constants {
public static final String INVOICE = "INVOICE";
public static final String ORDER = "ORDER";
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = Document.TYPE)
@JsonSubTypes({
@JsonSubTypes.Type(value = Invoice.class, name = DocTypeEnum.Constants.INVOICE),
@JsonSubTypes.Type(value = Order.class, name = DocTypeEnum.Constants.ORDER)
})
public class Document {
public static final String TYPE = "type";
public static final String TITLE = "title";
private final DocTypeEnum type;
private final String title;
public Document(DocTypeEnum type, String title) {
this.type = type;
this.title = title;
}
@JsonProperty(TYPE)
public DocTypeEnum getType() {
return type;
}
@JsonProperty(TITLE)
public String getTitle() {
return title;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Invoice extends Document {
public static final String DUE_DATE = "due_date";
private final Date dueDate;
public Invoice(String title, Date dueDate) {
super(DocTypeEnum.INVOICE, title);
this.dueDate = dueDate;
}
@JsonProperty(DUE_DATE)
public Date getDueDate() {
return dueDate;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends Document {
public static final String ITEMS = "items";
private final List<LineItems> items;
public Order(String title, List<LineItems> items) {
super(DocTypeEnum.ORDER, title);
this.items = items;
}
@JsonProperty(ITEMS)
public List<LineItems> getItems() {
return items;
}
}