简体   繁体   中英

Jackson - treat empty collection as null during serialization to json

Suppose that I have the following POJO

public class Pojo {
   private Set<String> stringSet = new HashSet<>();
}

When I do serialize it to the json, I've got the following output

{"stringSet":[]}

However, per requirements, I need the following:

{"stringSet":null}

I have tried to implement the custom StdSerializer<Set>

public class CustomStdSerializer extends StdSerializer<Set> {
    protected CustomStdSerializer() {
        super(Set.class);
    }

    @Override
    public void serialize(Set set, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (set.size() == 0){
            jsonGenerator.writeNull();
        }

    }
}

But the output of it is the following

{"stringSet":}

How can I write null value in json?

I had the exact same requirement a while ago.

The reason why you get a [] stringSet is because during declaration itself you are doing new HashSet<>();

and i am quite sure that in your setter method you might be simply doing

public void setStringSet(Set<String> stringSet){
   this.stringSet = stringSet;
}

instead you could do

public void setStringSet(Set<String> stringSet){
   if(stringSet.isEmpty()){
      this.stringSet.clear();
   } else{
      this.stringSet = stringSet;
   }
}

and this just worked fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM