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":""}
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;
}
}
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 {
...
}
and then
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…