2012-11-14 21 views
8

Sto usando Jackson 2.1.0. Dato:Perché @JsonUnwrapped non funziona per gli elenchi?

public static final class GetCompanies 
{ 
    private final List<URI> companies; 

    /** 
    * Creates a new GetCompanies. 
    * <p/> 
    * @param companies the list of available companies 
    * @throws NullPointerException if companies is null 
    */ 
    @JsonCreator 
    public GetCompanies(@JsonUnwrapped @NotNull List<URI> companies) 
    { 
     Preconditions.checkNotNull(companies, "companies"); 

     this.companies = ImmutableList.copyOf(companies); 
    } 

    /** 
    * @return the list of available companies 
    */ 
    @JsonUnwrapped 
    @SuppressWarnings("ReturnOfCollectionOrArrayField") 
    public List<URI> getCompanies() 
    { 
     return companies; 
    } 
} 

Quando l'elenco di input contiene http://test.com/, Jackson genera:

{"companies":["http://test.com/"]} 

invece di:

["http://test.com/"] 

Tutte le idee?

UPDATE: Vedere https://github.com/FasterXML/jackson-core/issues/41 per una discussione correlata.

risposta

16

In questo caso, se questo è stato quello di lavorare, che ci si finisce per cercare di produrre seguente:

{ "http://test.com" } 

che non è JSON legale. @JsonUnwrapped rimuove davvero solo uno strato di avvolgimento. E anche se teoricamente potrebbe essere fatto funzionare per il caso "array in array", non lo è. E in effetti mi chiedo se l'aggiunta di questa funzione sia stata un errore: principalmente perché incoraggia l'utilizzo che è spesso contro le best practice vincolanti i dati (semplicità, mappatura one-to-one).

Ma quello che avrebbe funzionato invece è @JsonValue:

@JsonValue 
private final List<URI> companies; 

che significa "valore d'uso della struttura, invece di serializzazione l'oggetto che lo contiene".

E il metodo creatore funzionerebbe effettivamente così com'è, non è necessario né per @JsonUnwrapped né per @JsonProperty.

Ecco il codice corretto:

public static final class GetCompanies 
{ 
    private final List<URI> companies; 

    /** 
    * Creates a new GetCompanies. 
    * <p/> 
    * @param companies the list of available companies 
    * @throws NullPointerException if companies is null 
    */ 
    @JsonCreator 
    public GetCompanies(@NotNull List<URI> companies) 
    { 
     Preconditions.checkNotNull(companies, "companies"); 

     this.companies = ImmutableList.copyOf(companies); 
    } 

    /** 
    * @return the list of available companies 
    */ 
    @JsonValue 
    @SuppressWarnings("ReturnOfCollectionOrArrayField") 
    public List<URI> getCompanies() 
    { 
     return companies; 
    } 
} 
Problemi correlati