2014-03-24 1 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» в вашем случае. Исключения Json будут выбрасываться, если у вас есть несколько параметров в конструкторе Builder, если вы оставите «@JsonProperty» пустым. – volatilevar

Смежные вопросы