为什么@JsonUnwrapped 不适用于列表? [英] Why doesn't @JsonUnwrapped work for Lists?

查看:24
本文介绍了为什么@JsonUnwrapped 不适用于列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Jackson 2.1.0.鉴于:

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

当输入列表包含 http://test.com/ 时,Jackson 生成:

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

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

代替:

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

有什么想法吗?

更新:参见 https://github.com/FasterXML/jackson-core/issues/41 相关讨论.

推荐答案

在这种情况下,如果这样做可行,您最终会尝试生成以下内容:

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

{ "http://test.com" }

这不是合法的 JSON.@JsonUnwrapped 实际上只是去除了一层包装.尽管理论上可以使其适用于数组中的数组"情况,但事实并非如此.事实上,我想知道添加此功能是否是一个错误:主要是因为它鼓励使用通常违反数据绑定最佳实践(简单性、一对一映射).

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).

但是可以使用的是 @JsonValue:

@JsonValue
private final List<URI> companies;

这意味着使用这个属性的值而不是序列化包含它的对象".

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

并且创建者方法实际上可以按原样工作,不需要 @JsonUnwrapped@JsonProperty.

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

这是更正后的代码:

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

这篇关于为什么@JsonUnwrapped 不适用于列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆