[英]How can i generate JSON schema with a required filed or default values?
im using jackson to handle JSON objects, and i want a way to generate a schema from a class that i can enforce on the objects.我使用杰克逊来处理 JSON 对象,我想要一种方法来从我可以对对象强制执行的类生成模式。 i found out that i can use this :
我发现我可以使用这个:
JsonSchemaGenerator generator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = generator.generateSchema(DBUser.class);
mapper.writeValueAsString(jsonSchema);
using this com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator.使用这个 com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator。
generated from this class:从这个类生成:
public class DBUser {
private String database="stu";
private int role;
private String username;
private String password;
//setters and getters defined
}
which gives me this :这给了我这个:
{
"type" : "object",
"id" : "urn:jsonschema:DBUser",
"properties" : {
"database" : {
"type" : "string"
},
"role" : {
"type" : "integer"
},
"username" : {
"type" : "string"
},
"password" : {
"type" : "string"
}
}
}
what i need is a required field like this :我需要的是这样的必填字段:
"required": ["database","role","username"]
but it has no required field, or initial values, which i need.但它没有我需要的必填字段或初始值。 so how can i get that ?
那我怎么能得到呢?
You can annotate your pojo DBUser
class fields with the JsonProperty#required
set to true
to generate a jsonschema with required fields:您可以使用
JsonProperty#required
设置为true
来注释您的 pojo DBUser
类字段,以生成带有必填字段的 jsonschema:
public class DBUser {
@JsonProperty(required = true)
private String database = "stu";
@JsonProperty(required = true)
private int role;
@JsonProperty(required = true)
private String username;
private String password;
}
//generate the new jsonschema with the required fields
JsonSchemaGenerator generator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = generator.generateSchema(DBUser.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(jsonSchema));
//json generated
{
"type" : "object",
"id" : "urn:jsonschema:DBUser",
"properties" : {
"database" : {
"type" : "string",
"required" : true
},
"role" : {
"type" : "integer",
"required" : true
},
"username" : {
"type" : "string",
"required" : true
},
"password" : {
"type" : "string"
}
}
}
Note that according to the documentation the jsonschema module supports the creation of a JSON Schema (v3) and not upper JSON Schema versions, so keywords introduced in later versions are not supported.请注意,根据文档,jsonschema 模块支持创建 JSON Schema (v3) 而不是更高的 JSON Schema 版本,因此不支持更高版本中引入的关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.