2016-07-22 60 views
0

我用jacksonjackson-module-jsonSchema反序列化JSON和生成JSON模式(飛)由json-schema-validator驗證JSON。傑克遜jsonSchema:如何設置類型的對象財產(JsonRawValue)

我有一個類與字段「有效載荷」。該字段應該包含原始json,因爲可以有任何屬性,客戶端需要。例如:

{ 
    "author": "test", 
    "payload": { 
     "title": "Test title" 
    } 
} 

我期待那場有效載荷,將有型「對象」的模式,但它的類型「string」。我應該如何告訴計劃生成器使其成爲對象?

類:

import com.fasterxml.jackson.annotation.JsonRawValue; 
import com.fasterxml.jackson.databind.JsonNode; 

public class Book { 
    private String author; 
    private Object payload; 

    @JsonRawValue 
    public Object getPayload() { 
     return payload; 
    } 

    public void setPayload(JsonNode node) { 
     this.payload = node; 
    } 

    public String getAuthor() { 
     return author; 
    } 

    public void setAuthor(String author) { 
     this.author = author; 
    } 

    @Override 
    public String toString() { 
     return "Book{" + 
      "author='" + author + '\'' + 
      ", payload=" + payload + 
      '}'; 
    } 
} 

我的測試:

@Test 
public void generateSchemaBook() throws Exception { 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.registerModule(new SimpleModule()); 
    JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); 
    final JsonSchema jsonSchema = schemaGen.generateSchema(Book.class); 
    jsonSchema.set$schema("http://json-schema.org/draft-03/schema#"); 
    final String schema = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema); 
    /* 
     { 
      "type" : "object", 
      "id" : "urn:jsonschema:ru:infon:mas:protocol:Book", 
      "$schema" : "http://json-schema.org/draft-03/schema#", 
      "properties" : { 
      "author" : { 
       "type" : "string", 
       "required" : true 
      }, 
      "payload" : { 
       "type" : "string", 
       "required" : true 
      } 
      } 
     } 
    */ 
    System.out.println(schema); 
    String testJson = "{\"author\":\"test\",\"payload\":{\"title\":\"Test title\"}}"; 
    Book book = mapper.readValue(testJson, Book.class); 
    System.out.println(book); 
    assertEquals("{\"title\":\"Test title\"}", book.getPayload().toString()); 

    ProcessingReport validate = JsonSchemaFactory.byDefault().getJsonSchema(JsonLoader.fromString(schema)).validate(JsonLoader.fromString(testJson)); 
    assertTrue(validate.isSuccess()); 
} 

回答

0

我沒有找到解決辦法要做到這一點就飛和決定產生JSON模式的一次,把它放到文件和加載。