我使用jackson和jackson-module-jsonSchema反序列化json并生成json模式(在运行中)以json-schema-validator验证json。
我有一个带有字段"有效载荷"的类。该字段应包含原始json,因为可以有客户端需要的任何属性。例如:
{
"author": "test",
"payload": {
"title": "Test title"
}
}
我希望字段有效负载的类型为" object"在架构中,但它的类型"字符串"。如何告诉方案生成器使其成为对象???
类别:
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 :(得分:0)
我没有找到解决办法在飞行中执行此操作并决定生成一次json架构,将其放入文件并加载。