0
我有以下類: 傑克遜:使用建設者與非默認構造
@JsonDeserialize(builder = Transaction.Builder.class)
public final class Transaction {
@JacksonXmlText
private final TransactionType transactionType;
@JacksonXmlProperty(isAttribute = true)
private final boolean transactionAllowed;
private Transaction(Builder builder) {
transactionType = builder.transactionType;
transactionAllowed = builder.transactionAllowed;
}
public static final class Builder {
private final TransactionType transactionType;
private boolean transactionAllowed;
public Builder(TransactionType transactionType) {
this.transactionType = transactionType;
}
public Builder withTransactionAllowed() {
transactionAllowed = true;
return this;
}
public Transaction build() {
return new Transaction(this);
}
}
}
TransactionType
是一個簡單枚舉:
public enum TransactionType {
PU,
CV;
}
當我創建一個新的交易實例,並使用傑克遜序列化mapper我得到以下xml:
<transaction transactionAllowed="true">PU</transaction>
問題是我無法反序列化它。我得到以下異常:
com.fasterxml.jackson.databind.JsonMappingException:
No suitable constructor found for type [simple type, class Transaction$Builder]
如果我把@JsonCreator在Builder構造是這樣的:
@JsonCreator
public Builder(TransactionType transactionType) {
this.transactionType = transactionType;
}
我得到以下異常:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct
instance of Transaction from String value 'transactionAllowed': value not one of
declared Enum instance names: [PU, CV]
如果我再放入@JsonProperty這樣的構造參數:
@JsonCreator
public Builder(@JsonProperty TransactionType transactionType) {
this.transactionType = transactionType;
}
我得到另一個錯誤:
com.fasterxml.jackson.databind.JsonMappingException: Could not find creator
property with name '' (in class Transaction$Builder)
任何想法如何解決這個問題?
對於「@JsonProperty」,你應該填寫屬性的名稱,在你的情況下應該是「transactionType」。如果將「@JsonProperty」留空,則在Builder構造函數中有多個參數時,將拋出Json異常。 – volatilevar