2013-10-03 50 views
6

當使用Jackson的JSON模式模塊時,不是序列化完整的圖表,我想在遇到我的模型類之一時停止,並使用類名爲另一個模式插入$ ref 。你能指導我到jackson-module-jsonSchema源碼的正確位置開始修補嗎?Jackson:使用引用生成模式

下面是一些代碼來說明這個問題:

public static class Zoo { 
    public String name; 
    public List<Animal> animals; 
} 

public static class Animal { 
    public String species; 
} 

public static void main(String[] args) throws Exception { 
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); 

    ObjectMapper mapper = objectMapperFactory.getMapper(); 
    mapper.acceptJsonFormatVisitor(mapper.constructType(Zoo.class), visitor); 
    JsonSchema jsonSchema = visitor.finalSchema(); 

    System.out.println(mapper.writeValueAsString(jsonSchema)); 
} 

輸出:

{ 
    "type" : "object", 
    "properties" : { 
    "animals" : { 
     "type" : "array", 
     "items" : { 
     "type" : "object", 
     "properties" : {   <---- Animal schema is inlined :-(
      "species" : { 
      "type" : "string" 
      } 
     } 
     } 
    }, 
    "name" : { 
     "type" : "string" 
    } 
    } 
} 

所需的輸出:

{ 
    "type" : "object", 
    "properties" : { 
    "animals" : { 
     "type" : "array", 
     "items" : { 
     "$ref" : "#Animal"  <---- Reference to another schema :-) 
     } 
    }, 
    "name" : { 
     "type" : "string" 
    } 
    } 
} 

回答

0

您可以嘗試使用下面的代碼 -

ObjectMapper MAPPER = new ObjectMapper(); 
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); 

    JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER); 

    JsonSchema jsonSchema = generator.generateSchema(MyBean.class); 

    System.out.println(MAPPER.writeValueAsString(jsonSchema)); 

但你的預期輸出是無效的,也不會說$裁判,除非它已指定「動物」的模式至少一次。

{ 
    "type": "object", 
    "id": "urn:jsonschema:com:tibco:tea:agent:Zoo", 
    "properties": { 
     "animals": { 
      "type": "array", 
      "items": { 
       "type": "object", 
       "id": "urn:jsonschema:com:tibco:tea:agent:Animal", 
       "properties": { 
        "species": { 
         "type": "string" 
        } 
       } 
      } 
     }, 
     "name": { 
      "type": "string" 
     } 
    } 
} 
2

您可以使用HyperSchemaFactoryWrapper而不是SchemaFactoryWrapper。通過這種方式,您將獲得嵌套實體的金字塔參考:

HyperSchemaFactoryWrapper visitor= new HyperSchemaFactoryWrapper(); 
ObjectMapper mapper = objectMapperFactory.getMapper(); 
mapper.acceptJsonFormatVisitor(mapper.constructType(Zoo.class), visitor); 
JsonSchema jsonSchema = visitor.finalSchema(); 

System.out.println(mapper.writeValueAsString(jsonSchema)); 
+0

對我沒有效果。仍然生成ReferenceSchema,而不是解析的。 –