0
我用jackson和jackson-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());
}