How to disable Jackson serializer on required attributes that are null

I would like the Jackson JSON serializer to fail if it encounters required attributes that are null.

I know I can specify empty fields ( mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)

). However, in addition, I would like to declare

@NotNull // BeanValidation
private String foo;

      

or

@JsonProperty(required = true) // Jackson databinding
private String foo;

      

and the serializer fails if such fields are null.

+3


source to share


1 answer


I don't see any annotation or configuration option for this. You can use hibernate-validator to validate the object before serialization. Since you don't want to add custom annotations, you can change the default serializer by inspecting your objects before serializing.

First, create your own serializer that takes another constructor argument and uses the hibernate validator to validate objects and throw exceptions.

class ValidatingSerializer extends JsonSerializer<Object> {
    private final JsonSerializer<Object> defaultSerializer;
    private final Validator validator;

    ValidatingSerializer(final JsonSerializer<Object> defaultSerializer) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        this.validator = factory.getValidator();
        this.defaultSerializer = defaultSerializer;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        if (!validator.validate(value).isEmpty()) {
            throw new IOException("Null value encountered");
        }
        defaultSerializer.serialize(value, gen, provider);
    }
}

      

Then create a serialization modifier that this serializer will use:

class ValidatingSerializerModifier extends BeanSerializerModifier {
    @Override
    public JsonSerializer<?> modifySerializer(SerializationConfig config,
             BeanDescription beanDesc, JsonSerializer<?> serializer) {
        return new ValidatingSerializer((JsonSerializer<Object>) serializer);
    }
}

      



Finally, log this to you ObjectMapper

with SimpleModule

:

SimpleModule module = new SimpleModule();
module.setSerializerModifier(new ValidatingSerializerModifier());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

      

This will now be used and exceptions will be thrown whenever validation fails for fields annotated with standard validation annotations:

@NotNull // BeanValidation
private String foo;

      

+2


source







All Articles