使用多个SchemaFactoryWrapper实例的杰克逊模式中的自定义属性

时间:2019-07-19 20:09:18

标签: java jackson jsonschema

我正在使用ValdationSchemaFactoryWarapper类在JSON模式中生成验证属性,并且我也需要将自己的自定义属性添加到模式中。如果开发自定义SchemaFactoryWrapper,则只能使用其中之一,而不能同时使用两者。

我可以通过使用以下代码扩展ValidationSchemaFactoryWrapper来实现所需的功能,但是,我想知道是否可能有一种更简单的方法,即使用两个单独的SchemaFactoryWrapper实例。

public class ConfigSchemaExtension {

    public static class ConfigSchemaFactoryWrapper extends ValidationSchemaFactoryWrapper {

        private static class SchemaFactoryWrapperFactory extends WrapperFactory {
            private SchemaFactoryWrapperFactory() {
            }

            public SchemaFactoryWrapper getWrapper(SerializerProvider p) {
                SchemaFactoryWrapper wrapper = new ConfigSchemaFactoryWrapper();
                wrapper.setProvider(p);
                return wrapper;
            }

            public SchemaFactoryWrapper getWrapper(SerializerProvider p, VisitorContext rvc) {
                SchemaFactoryWrapper wrapper = new ConfigSchemaFactoryWrapper();
                wrapper.setProvider(p);
                wrapper.setVisitorContext(rvc);
                return wrapper;
            }
        }

        public ConfigSchemaFactoryWrapper() {
            super(new AnnotationConstraintResolver());
            schemaProvider = new ConfigJsonSchemaFactory();
            visitorFactory = new FormatVisitorFactory(new SchemaFactoryWrapperFactory());
        }
    }

    public static class ConfigJsonSchemaFactory extends JsonSchemaFactory {
        @Override
        public com.fasterxml.jackson.module.jsonSchema.types.StringSchema stringSchema() {
            return new ConfigStringSchema();
        }
    }

    public static class ConfigStringSchema extends StringSchema {

        @JsonProperty
        private String myLink;

        @Override
        public void enrichWithBeanProperty(BeanProperty beanProperty) {
            super.enrichWithBeanProperty(beanProperty);
            Reference ref = beanProperty.getAnnotation(Reference.class);
            if(ref != null) this.myLink = ref.value(); 
        }
    }

    @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @JacksonAnnotation
    public @interface Reference
    {
        String value() default "";
    }
}```

0 个答案:

没有答案