jsonschema2pojo继承JSON Schema后无法将原必填字段设为可选问题
问题原因
- JSON Schema的
$ref关键字规则限制:如果一个对象内包含$ref属性,同层级的其他属性会被解析器直接忽略,你在allOf数组内和$ref同层级写的required: ["name"]规则完全没有生效。 - JSON Schema的组合逻辑限制:
allOf关键字代表所有子规则必须同时满足,你引入的父Schema已经要求三个字段全部必填,即使你补充的required规则生效,也只会在三个必填的基础上新增要求name必填,无法移除已有的必填约束。 - jsonschema2pojo扩展属性规则:你在字段内写的
isRequired是jsonschema2pojo的自定义扩展属性,生成Java类时会根据该值为字段添加@NotNull等校验注解,父类已经生成的注解不会因为子类的allOf规则自动移除,所以API文档扫描时仍会识别为必填。
解决方案
方案1:子类重写字段覆盖必填属性(适合需要保留Java类继承关系的场景)
直接在子类Schema中重新声明需要修改必填性的字段,将isRequired设为false,同时配置jsonschema2pojo插件允许子类属性覆盖父类:
{ "$schema": "http://json-schema.org/draft/2019-09/schema", "title": "Other Schema", "type": "object", "javaType": "..json_schema_model.dto.OtherSchema", "description": "Other Schema Description", "extendsJavaClass": "..json_schema_model.dto.PersonSchema", "properties": { "birthday": { "title": "Date of birth", "$ref": "resource:schema/general/dateSchema.json", "isRequired": false }, "birthCountry": { "$ref": "resource:schema/general/countrySchema.json", "title": "Country of birth", "isRequired": false }, "name": { "title": "Last name", "type": "string", "minLength": 1, "isRequired": true } } }
然后在你的pom.xml或者gradle配置的jsonschema2pojo插件参数中添加以下配置:
<!-- Maven 配置示例 --> <plugin> <groupId>org.jsonschema2pojo</groupId> <artifactId>jsonschema2pojo-maven-plugin</artifactId> <configuration> <!-- 允许子类覆盖父类的属性配置 --> <overrideAllProperties>true</overrideAllProperties> <includeRequiredProperties>true</includeRequiredProperties> </configuration> </plugin>
方案2:抽离公共字段分别定义(更符合JSON Schema原生规范)
JSON Schema本身不支持“减少约束”的继承逻辑,更推荐把公共字段抽成独立的公共定义块,两个业务Schema分别引用后自行定义必填规则,避免继承带来的约束冲突:
// 公共字段定义:commonPersonFields.json { "properties": { "name": { "title": "Last name", "type": "string", "minLength": 1 }, "birthday": { "title": "Date of birth", "$ref": "resource:schema/general/dateSchema.json" }, "birthCountry": { "$ref": "resource:schema/general/countrySchema.json", "title": "Country of birth" } } }
// 原PersonSchema { "$schema": "http://json-schema.org/draft/2019-09/schema", "title": "Person Schema", "type": "object", "javaType": "..json_schema_model.dto.PersonSchema", "allOf": [ {"$ref": "resource:schema/general/commonPersonFields.json"} ], "required": ["name", "birthday", "birthCountry"] }
// 新OtherSchema { "$schema": "http://json-schema.org/draft/2019-09/schema", "title": "Other Schema", "type": "object", "javaType": "..json_schema_model.dto.OtherSchema", "description": "Other Schema Description", "allOf": [ {"$ref": "resource:schema/general/commonPersonFields.json"} ], "required": ["name"] }
这个方案不需要修改插件配置,也符合JSON Schema的标准语义,后续维护成本更低。
内容的提问来源于stack exchange,提问作者Katharina
相关产品推荐
相关产品推荐

