Why doesn't @JsonUnwrapped work for Lists?

前端 未结 1 954
一个人的身影
一个人的身影 2020-12-06 05:15

I am using Jackson 2.1.0. Given:

public static final class GetCompanies
{
    private final List companie         


        
相关标签:
1条回答
  • 2020-12-06 05:50

    In this case, if this was to work, you'd end up trying to produce following:

    { "http://test.com" }
    

    which is not legal JSON. @JsonUnwrapped really just removes one layer of wrapping. And although it theoretically could be made to work for "arrays in arrays" case, it does not. And in fact I wonder if adding this feature was a mistake: mostly because it encourages use that is often against data-binding best practices (simplicity, one-to-one mapping).

    But what would work instead is @JsonValue:

    @JsonValue
    private final List<URI> companies;
    

    which means "use value of this property instead of serializing the object that contains it".

    And the creator method would actually work as-is, no need for either @JsonUnwrapped or @JsonProperty.

    Here is the corrected code:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题