Why doesn't @JsonUnwrapped work for Lists?

前端 未结 1 964
一个人的身影
一个人的身影 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 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 companies;
    
        /**
         * Creates a new GetCompanies.
         * 

    * @param companies the list of available companies * @throws NullPointerException if companies is null */ @JsonCreator public GetCompanies(@NotNull List companies) { Preconditions.checkNotNull(companies, "companies"); this.companies = ImmutableList.copyOf(companies); } /** * @return the list of available companies */ @JsonValue @SuppressWarnings("ReturnOfCollectionOrArrayField") public List getCompanies() { return companies; } }

    0 讨论(0)
提交回复
热议问题