杰克逊反序列化“”作为一个空列表 [英] Jackson deserialize "" as an empty list
问题描述
我有一个JSON字符串,将空列表标记为而不是
[]
。例如,如果我有一个没有子节点的对象,我会收到一个这样的字符串:
I have a JSON string that marks empty lists as ""
instead of []
. So for example, if I have an object with no children, I'll receive a string like this:
{"id":13, "children":""}
我想将它反序列化为Parent类,将孩子正确设置为空子列表。
I'd like to deserialize that to a Parent class, with children properly set to an empty list of children.
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
设置为新的ArrayList< Child>()
For the above JSON string, I'd like an object that will have its id
set to 13
, and the children
set to a new ArrayList<Child>()
Parent
id <- 13
children <- new ArrayList<Child>()
我知道如何为整个班级使用注释
I would know how to use an annotation for the entire class
@JsonDeserialize(using = ParentDeserializer.class)
public class Parent {
...
}
然后
public class ParentDeserializer extends JsonDeserializer<Parent> {
public Parent deserialize(JsonParser parser, DeserializationContext context) {
...
}
}
但是,我想解决从字符串中正确实例化列表的一般问题:
However, I'd like to solve a general problem of instantiating Lists properly from ""
strings:
public class Parent {
...
// Can I get something like this?
@JsonDeserialize(using = EmptyArrayDeserializer<Child>.class)
public void setChildren(List<Child> children) {
this.children = children;
}
}
我能得到类似的东西吗?
Can I get something like that?
推荐答案
多种选择;首先,您要启用`ACCEPT_EMPTY_STRING_AS_NULL_OBJECT':
Couple of options; first, you want to enable `ACCEPT_EMPTY_STRING_AS_NULL_OBJECT':
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
以便空字符串变为空。如果你想让它转换为实际的空列表,覆盖setter:
so that empty String becomes null. And if you want it to get converted to actual empty List, override setter:
public void setChildren(List<Child> c) {
if (c == null) {
children = Collections.emptyList();
} else {
chidlren = c;
}
}
这篇关于杰克逊反序列化“”作为一个空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!