I want to write a custom serializer that, when it encounters a null value for a set, serializes it as an empty set. I want to pair that with a deserializer which deserializes an empty set back to null. If the collection has elements, it can be serialized/deserialized as normal.
I've written a couple of deserializers and they work well but the methods I used there don't seem applicable to collections. For example, I wrote this to turn empty strings into nulls:
JsonNode node = p.readValueAsTree();
String text = (Objects.isNull(node) ? null : node.asText());
if (StringUtils.isEmpty(text)) {
return null;
}
I don't think this will work because JsonNode doesn't have an asSet() method.
I've found examples online that look promising but it seems like all the examples of working with collections involve working with the elements inside the collection, not the collection itself.
So far, I've been hand-coding this process but I'm sure there's a better way to deal with it.
I'm at the point of figuring it out by trial and error so any examples, ideas, or advice would be appreciated.
Here's what I'm thinking it should look like:
@JsonComponent
public class SetDeserializer extends Std???Deserializer<Set<?>> {
public SetDeserializer() {
super(Set.class);
}
@Override
public Set<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = p.readValueAsTree();
Set<?> mySet = (Objects.isNull(node) ? null : node.asSet());
if (CollectionUtils.isEmpty(mySet)) {
return null;
}
return super().deserialize(p, ctxt);
}
}