Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...