使用jsonschema2pojo-core生成POJO时遇additionalProperties重复字段错误
解决jsonschema2pojo-core 1.0.2生成POJO时重复创建additionalProperties字段的问题
问题重现
使用jsonschema2pojo-core 1.0.2版本将JSON Schema转换为POJO时,抛出错误:trying to create the same field twice: additionalProperties
所用代码
class JsonToPojo { public static void main(String[] args) throws IOException { JCodeModel codeModel = new JCodeModel(); URL source = JsonToPojo.class.getResource("/test.json"); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { // 设置配置项 return true; } @Override public SourceType getSourceType() { return SourceType.JSON; } }; SchemaMapper mapper = new SchemaMapper( new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator()); mapper.generate(codeModel, "JsonToPojo", "com.controller", source); File file = Files.createTempDirectory("required").toFile(); codeModel.build(file); System.out.println("path is " + file); } }
目标JSON Schema
{ "$id": "https://example.com/person.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Person", "type": "object", "properties": { "firstName": { "type": "string", "description": "The person's first name." }, "lastName": { "type": "string", "description": "The person's last name." }, "age": { "description": "Age in years which must be equal to or greater than zero.", "type": "integer", "minimum": 0 } } }
问题原因
核心错误是你将SourceType指定为JSON,但输入文件实际是JSON Schema。jsonschema2pojo对普通JSON实例和JSON Schema的处理逻辑不同:
- 当SourceType为
JSON时,工具会把输入当作具体的JSON数据,尝试解析所有顶层属性; - 工具默认会为对象类型生成
additionalProperties字段来处理未定义属性,两者叠加导致字段重复创建冲突。
解决方案
修改GenerationConfig中的getSourceType方法,返回SourceType.JSONSCHEMA,明确告知工具输入是JSON Schema:
GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { return true; } @Override public SourceType getSourceType() { return SourceType.JSONSCHEMA; // 替换为JSONSCHEMA } };
验证结果
修改后生成的POJO会完全符合你的期望,包含:
firstName、lastName、age三个属性及对应的getter/setter方法additionalProperties的Map字段,搭配@JsonAnyGetter和@JsonAnySetter注解处理额外属性
内容的提问来源于stack exchange,提问作者Anuj Sharma
相关产品推荐
相关产品推荐

