Java 通过Jackson生成JsonSchema("additionalProperties" : false)
时间:2023-01-05
1、使用Maven引用mbknor-jackson-jsonschema_2.12
<dependency> <groupId>com.kjetland</groupId> <artifactId>mbknor-jackson-jsonschema_2.12</artifactId> <version>1.0.28</version> </dependency>
2、生成JsonSchema("additionalProperties" : false)
1)需要import的包
import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.kjetland.jackson.jsonSchema.JsonSchemaConfig;import com.kjetland.jackson.jsonSchema.JsonSchemaGenerator;
2)生成JsonSchema代码
ObjectMapper objectMapper = new ObjectMapper(); JsonSchemaConfig config = JsonSchemaConfig.nullableJsonSchemaDraft4(); JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator(objectMapper, config); JsonNode jsonNode = schemaGenerator.generateJsonSchema(Test.hljs-button" data-title="在线运行" onclick="runCode(2)">
3)生成的jsonSchemaText
Test.java:
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public >Test { @JsonProperty(required = true) private final String name; private final TestChild child; @JsonCreator public Test ( @JsonProperty("name") String name, @JsonProperty("child") TestChild child) { this.name = name; this.child = child; } public String getName () { return name; } public TestChild getChild () { return child; } }
TestChild.java:
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public >TestChild { @JsonProperty(required = true) private final String childName; @JsonCreator public TestChild (@JsonProperty("childName") String childName) { this.childName = childName; } public String getChildName () { return childName; } }
jsonSchemaText:
{ "$schema": "", "title": "Test", "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string" }, "child": { "oneOf": [ { "type": "null", "title": "Not included" }, { "$ref": "#/definitions/TestChild" } ] } }, "required": [ "name" ], "definitions": { "TestChild": { "type": "object", "additionalProperties": false, "properties": { "childName": { "type": "string" } }, "required": [ "childName" ] } } }
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。