Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

jackson - Why doesn't @JsonUnwrapped work for Lists?

I am using Jackson 2.1.0. Given:

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

When the input list contains http://test.com/, Jackson generates:

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

instead of:

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

Any ideas?

UPDATE: See https://github.com/FasterXML/jackson-core/issues/41 for a related discussion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...