2014-04-01 56 views
0

我有一個類,說:如何自定義添加註解傑克遜模式

class Data { 
    public int value; 
}; 

,我想生成JSON模式使用傑克遜架構模塊與數據字段的有效範圍,如:

class Data { 
    @JsonProperties(min = 1) 
    @JsonProperties(max = 100) 
    public int value; 
}; 

但我在jackson-schema的wiki中搜索,它不支持這個,有沒有一些例子可以讓我們自定義註釋?謝謝

回答

0

這樣做的一個項目是JJSchema。 JSON Schea的傑克遜模塊目前沒有這樣的細粒度控制。

1

有一種方法可以包括自定義註釋傑克遜的模式,但你需要如下創建幾類,我用它來添加我的自定義title屬性:

  1. 創建自己的SchemaFactoryWrapper

    public static class YourselfSchemaFactoryWrapper extends SchemaFactoryWrapper{ 
        private static class YourselfSchemaFactoryWrapperFactory extends WrapperFactory { 
         @Override 
         public SchemaFactoryWrapper getWrapper(SerializerProvider p) { 
          SchemaFactoryWrapper wrapper = new YourselfSchemaFactoryWrapper(); 
          if (p != null) { 
           wrapper.setProvider(p); 
          } 
          return wrapper; 
         }; 
    
         @Override 
         public SchemaFactoryWrapper getWrapper(SerializerProvider p, VisitorContext rvc) { 
          SchemaFactoryWrapper wrapper = new YourselfSchemaFactoryWrapper(); 
          if (p != null) { 
           wrapper.setProvider(p); 
          } 
          wrapper.setVisitorContext(rvc); 
          return wrapper; 
         } 
        }; 
    
        public YourselfSchemaFactoryWrapper() { 
         super(new YourselfSchemaFactoryWrapperFactory()); 
         schemaProvider = new YourselfJsonSchemaFactory(); 
        } 
    } 
    
  2. 創建您自己的JsonSchemaFactory 您可以根據需要在此類中重寫JsonSchemaFactory的函數。對於這種情況,我只想重寫字符串模式。

    public class YourselfJsonSchemaFactory extends JsonSchemaFactory{ 
        @Override 
        public StringSchema stringSchema() { 
         return new YourselfStringSchema(); 
        } 
    } 
    
  3. 創建自己的StringSchema

    public class YourselfStringSchema extends StringSchema{ 
        @Override 
        public void enrichWithBeanProperty(BeanProperty beanProperty) { 
         super.enrichWithBeanProperty(beanProperty); 
         JsonPropertyTitle title = beanProperty.getAnnotation(JsonPropertyTitle.class); 
         if(title != null) this.setTitle(title.value()); 
        } 
    } 
    
  4. 然後定義自己的註釋

    @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) 
    @Retention(RetentionPolicy.RUNTIME) 
    @Documented 
    @JacksonAnnotation 
    public @interface JsonPropertyTitle 
    { 
        String value() default ""; 
    } 
    
  5. 最後,您可以使用此批註模型

    public class DataModal{ 
        @JsonPropertyTitle("My Custom Title") 
        private str; 
    } 
    
+0

這是工作。它不適合我。 – Dhepthi

+0

@Dhepthi我使用jackson-module-jsonSchema 2.8.3,我工作。你有什麼問題嗎? –

+0

非常感謝分享,偉大的工作..作品! –

1

您可以對此(javax.validation.*)使用Java驗證API。

javax.validation.constraints.Size

@Size(min = 1, max = 100, message = "error message") 
private String text; 
+0

這應該是一個評論,而不是一個答案,至少你可以解釋更多 –

+0

@Youcef編輯我的答案,從我的手機回答不正確組織。 –