2014-03-24 26 views
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) 

任何想法如何解決這個問題?

回答

0

所有我做了工作,寫這篇製造商後:

public static final class Builder { 
    @JacksonXmlText 
    private final TransactionType transactionType; 
    private boolean transactionAllowed; 

    @JsonCreator 
    public Builder(@JsonProperty(" ") TransactionType transactionType) { 
     this.transactionType = transactionType; 
    } 

    public Builder withTransactionAllowed() { 
     transactionAllowed = true; 
     return this; 
    } 

    public Transaction build() { 
     return new Transaction(this); 
    } 
} 

注意@JsonProperty的值不爲空,它實際上是除了一個空字符串的任何值。我不相信這是有史以來最好的解決方案,但它的工作原理。但我不會接受我自己的答案,因爲可能有更好的解決方案。

+0

對於「@JsonProperty」,你應該填寫屬性的名稱,在你的情況下應該是「transactionType」。如果將「@JsonProperty」留空,則在Builder構造函數中有多個參數時,將拋出Json異常。 – volatilevar