Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

json - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...