unbroken-dome / jackson-bean-validation

A Jackson module that performs Java Bean Validation during deserialization.
MIT License
21 stars 13 forks source link

@JsonTypeInfo Jacson annotation disables validation? #11

Open stanislawosinski opened 3 years ago

stanislawosinski commented 3 years ago

Excellent library! I was hoping to use it to validate polymorphic JSONs implemented using Jackson's @JsonTypeInfo annotation. Unfortunately, the use of this annotation appears to turn off the validation on the polymorphic object.

I include a quick reproduction test below. If you remove the @JsonTypeInfo annotation, validation will be performed as expected.

Is there any workaround I could use to make jackson-bean-validation work with @JsonTypeInfo?

public class ValidatorTest {
  @JsonValidated
  public static class Impl implements Interface {
    @JsonProperty @NotEmpty public String s;
  }

  @JsonValidated
  @JsonTypeInfo(use = Id.NAME, property = "type")
  @JsonSubTypes({@JsonSubTypes.Type(name = "default", value = Impl.class)})
  public interface Interface {}

  @Test
  public void validation() throws JsonProcessingException {
    final ObjectMapper om = new ObjectMapper();
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    final BeanValidationModule module = new BeanValidationModule(factory);
    om.registerModule(module);

    final Interface invalid = new Impl();
    final String invalidJson = om.writeValueAsString(invalid);

    try {
      om.readValue(invalidJson, Impl.class);
    } catch (ConstraintViolationException e) {
      return;
    }
    Assertions.fail("Expecting ConstraintViolationException");
  }
}