Skip to content

@JsonTypeInfo Jacson annotation disables validation? #11

@stanislawosinski

Description

@stanislawosinski

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions