You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:55:18