【问题标题】:Jackson deserialize "" as an empty listJackson 将 "" 反序列化为空列表
【发布时间】:2012-10-18 07:26:49
【问题描述】:

我有一个 JSON 字符串,它将空列表标记为 "" 而不是 []。例如,如果我有一个没有孩子的对象,我会收到这样的字符串:

{"id":13, "children":""}

我想将其反序列化为 Parent 类,并将孩子正确设置为一个空的孩子列表。

public class Parent {

    private Long id;
    private List<Child> children;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<Child> getChildren() {
        return children;
    }

    public void setChildren(List<Child> children) {
        this.children = children;
    }
}

对于上述 JSON 字符串,我想要一个将其 id 设置为 13 并将 children 设置为 new ArrayList&lt;Child&gt;() 的对象

Parent
    id <- 13
    children <- new ArrayList<Child>()

我会知道如何为整个班级使用注释

@JsonDeserialize(using = ParentDeserializer.class)
public class Parent { 
    ...
}

然后

public class ParentDeserializer extends JsonDeserializer<Parent> {
    public Parent deserialize(JsonParser parser, DeserializationContext context) {
        ...    
    }
}

但是,我想解决从"" 字符串正确实例化列表的一般问题:

public class Parent {
    ...
    // Can I get something like this?
    @JsonDeserialize(using = EmptyArrayDeserializer<Child>.class) 
    public void setChildren(List<Child> children) {
        this.children = children;
    }
}

我可以得到这样的东西吗?

【问题讨论】:

    标签: json spring jackson deserialization


    【解决方案1】:

    几个选项;首先,您要启用 `ACCEPT_EMPTY_STRING_AS_NULL_OBJECT':

    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    

    使空字符串变为空。如果您希望它转换为实际的空列表,请覆盖 setter:

    public void setChildren(List<Child> c) {
        if (c == null) {
           children = Collections.emptyList();
        } else {
           chidlren = c;
        }
    }
    

    【讨论】:

    • 这对收藏有用吗? github.com/FasterXML/jackson-databind/issues/91 标记为 open 表示它仅适用于单个对象。
    • 它确实有效——根据用户报告,我认为它没有,但它确实有效,并且有针对它的单元测试。 'OBJECT' 在这里表示任何 Java 对象。
    • 我可以确认它有效。我仍然对空列表的显式实例化感到不舒服(我希望反序列化器可以以通用的方式为我做到这一点),但它必须这样做。谢谢!
    • 明白。事情变得有问题,因为一些语言和库做了很多奇怪的事情(主要是像 Perl、JS 这样的脚本),很难找到简单和通用的处理——通常不兼容的数据是错误的,隐藏错误也不好。
    • @ipavlic 问题是顾名思义,空字符串变成null,而不是其他类型的对象
    猜你喜欢
    • 2023-03-13
    • 2018-05-31
    • 2018-05-09
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2012-08-19
    • 2021-11-08
    • 2016-08-05
    相关资源
    最近更新 更多