2012-11-14 26 views
8

Tôi đang sử dụng Jackson 2.1.0. Đưa ra:Tại sao không @JsonUnwrapped làm việc cho Danh sách?

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; 
    } 
} 

Khi danh sách đầu vào chứa http://test.com/, Jackson tạo:

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

thay vì:

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

ý tưởng Bất kỳ?

CẬP NHẬT: Xem https://github.com/FasterXML/jackson-core/issues/41 để có cuộc thảo luận liên quan.

Trả lời

16

Trong trường hợp này, nếu điều này là để làm việc, bạn muốn kết thúc cố gắng để sản xuất sau:

{ "http://test.com" } 

mà không phải là JSON pháp lý. @JsonUnwrapped thực sự chỉ cần loại bỏ một lớp gói. Và mặc dù về mặt lý thuyết nó có thể được thực hiện để làm việc cho "mảng trong mảng" trường hợp, nó không. Và trên thực tế, tôi tự hỏi liệu việc thêm tính năng này có phải là một sai lầm hay không: chủ yếu là vì nó khuyến khích sử dụng thường chống lại các thực hành tốt nhất ràng buộc dữ liệu (đơn giản, ánh xạ một đối một).

Nhưng điều gì sẽ làm việc thay vì là @JsonValue:

@JsonValue 
private final List<URI> companies; 

có nghĩa là "giá trị sử dụng tài sản này thay vì serializing đối tượng chứa nó".

Và phương pháp của người sáng tạo sẽ thực sự hoạt động như hiện trạng, không cần @JsonUnwrapped hoặc @JsonProperty.

Đây là mã đã sửa:

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; 
    } 
} 
Các vấn đề liên quan