Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson deserialize "" as an empty list

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?

like image 497
ipavlic Avatar asked Oct 17 '12 11:10

ipavlic


1 Answers

Couple of options; first, you want to enable `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;
    }
}
like image 124
StaxMan Avatar answered Nov 13 '22 05:11

StaxMan