1

我使用jacksonjackson-module-jsonSchema反序列化 json 并生成 json 模式(动态)以通过json-schema-validator验证 json 。

我有一个带有“有效载荷”字段的课程。该字段应包含原始 json,因为可以有任何客户需要的属性。例如:

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

我希望该字段有效负载在模式中具有“对象”类型,但它是“字符串”类型。我应该如何告诉方案生成器使其成为对象???

班级:

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());
}
4

1 回答 1

0

我没有找到即时执行此操作的解决方案,并决定生成一次 json 模式,将其放入文件并加载。

于 2016-08-01T08:47:14.587 回答