我有一个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<Child>()
id
13
children
new ArrayList<Child>()
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) { ... } }
但是,我想解决一个从""字符串正确实例化List的一般问题:
public class Parent { ... // Can I get something like this? @JsonDeserialize(using = EmptyArrayDeserializer<Child>.class) public void setChildren(List<Child> children) { this.children = children; } }
我能得到类似的东西吗?
几个选择;首先,您要启用`ACCEPT_EMPTY_STRING_AS_NULL_OBJECT’:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
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; } }