介绍
json-schema-inferrer 是一个json schema的java库,用来:根据json文档,生成对应的json schema文档。
- github地址:GitHub - saasquatch/json-schema-inferrer: Java library for inferring JSON schema from sample JSONs
- 在线演示:https://json-schema-inferrer.herokuapp.com/
特点:
- 支持输入多个json文档,经过计算后输出一个统一的json schema;
- 支持多种生成策略,例如:required、array length...
示例
1)mavne pom.xml
<dependency>
<groupId>com.github.saasquatch</groupId>
<artifactId>json-schema-inferrer</artifactId>
<version>0.1.1</version>
</dependency>
当前使用的是0.1.1版本。也可以在github 上的release上找对应的版本:Releases · saasquatch/json-schema-inferrer · GitHub
说明:json-schema-inferrer需要java8及以上,依赖Jackson 和FindBugs (JSR305),如果在生成过程中使用了FormatInferrers,Commons Validator 需要被引入。
2)示例代码:
public class Test {
private static final ObjectMapper mapper = new ObjectMapper();
private static final JsonSchemaInferrer inferrer = JsonSchemaInferrer.newBuilder()
.setSpecVersion(SpecVersion.DRAFT_04)
.setAdditionalPropertiesPolicy(AdditionalPropertiesPolicies.noOp())
.setRequiredPolicy(RequiredPolicies.noOp())
.build();
private static String json1 = "{\"a\":0,\"b\":[1,2]}";
public static void main(String... str) {
ObjectNode inferForSample = inferrer.inferForSample(mapper.readTree(json1));
System.out.println(inferForSample.toPrettyString());
}
}
输出:
{
"$schema" : "http://json-schema.org/draft-04/schema#",
"type" : "object",
"properties" : {
"a" : {
"type" : "integer"
},
"b" : {
"type" : "array",
"items" : {
"type" : "integer"
}
}
}
}
说明:在生成json schema时,可以通过JsonSchemaInferrer 来进行配置。例如:是否required...
3)示例2:
public class Test {
private static final ObjectMapper mapper = new ObjectMapper();
private static final JsonSchemaInferrer inferrer = JsonSchemaInferrer.newBuilder()
.setSpecVersion(SpecVersion.DRAFT_04)
.setAdditionalPropertiesPolicy(AdditionalPropertiesPolicies.noOp())
.setRequiredPolicy(RequiredPolicies.noOp())
.build();
private static String json1 = "{\"a\":0}";
private static String json2 = "{\"a\":,\"1\"}";
public static void main(String... str) {
ObjectNode inferForSamples2 = inferrer.inferForSamples(Arrays.asList(mapper.readTree(json1),mapper.readTree(json2)));
System.out.println(inferForSamples2.toPrettyString());
}
}
输出:
{
"$schema" : "http://json-schema.org/draft-04/schema#",
"type" : "object",
"properties" : {
"a" : {
"type" : [ "string", "integer" ]
}
}
}
说明:json-schema-inferrer支持将不同的json作为输入,该库会自动进行合并,然后生成一个统一的jsonschema。