もう1つのオプションは、多形処理をJacksonに委任するJongoを使用することです。私はいくつかの例を含むブログ投稿を書きました、そしてあなたは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;
}
}