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

Java RestTemplate版OpenAPI Generator:修改字段命名大小写策略

解决RestTemplate版OpenAPI Generator实体@JsonProperty命名格式问题

如果OpenAPI Generator没有提供直接配置项来修改@JsonProperty的命名格式,你可以通过以下几种方式覆盖默认行为:

1. 自定义Mustache模板(最直接方案)

OpenAPI Generator基于Mustache模板生成代码,你可以修改实体类模板中@JsonProperty的生成逻辑:

  • 获取对应模板:RestTemplate对应的Java实体模板通常是model.mustache或pojo.mustache,你可以从OpenAPI Generator的源码资源中复制一份到本地目录(比如./custom-templates)。
  • 修改模板内容:找到生成@JsonProperty注解的代码段,将原本的驼峰名称转换为蛇形/短横线格式。例如:
    原模板代码:
    @JsonProperty("{{name}}")
    public {{returnType}} {{getterName}}() {
        return {{fieldName}};
    }
    
    修改为蛇形命名(使用Mustache内置过滤器):
    @JsonProperty("{{name | snake_case}}")
    public {{returnType}} {{getterName}}() {
        return {{fieldName}};
    }
    
    若要改为短横线格式,替换为{{name | kebab_case}}即可。
  • 指定模板生成代码:执行生成命令时通过--template-dir参数指向自定义模板目录:
    openapi-generator generate -i openapi.yaml -g java --library resttemplate --template-dir ./custom-templates
    

2. 扩展Codegen类(适配复杂规则)

如果需要更灵活的命名转换逻辑,可以自定义Codegen类覆盖默认的命名处理:

  • 创建自定义Codegen类:继承JavaClientCodegen,重写toJsonPropertyName方法实现自定义转换:
    import org.openapitools.codegen.languages.JavaClientCodegen;
    import com.google.common.base.CaseFormat;
    
    public class CustomRestTemplateCodegen extends JavaClientCodegen {
        @Override
        public String toJsonPropertyName(String name) {
            // 驼峰转蛇形,可根据需求替换为其他转换规则
            return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
        }
    }
    
  • 打包并加载自定义Codegen:将类打包成JAR,放到OpenAPI Generator的类路径中。
  • 使用自定义Codegen生成代码:
    openapi-generator generate -i openapi.yaml -g com.your.package.CustomRestTemplateCodegen --library resttemplate
    

3. 生成后批量修改(临时快速方案)

如果不想修改模板或扩展生成器,可以在代码生成完成后,用工具批量修改实体类中的@JsonProperty值:

比如用JavaParser编写脚本处理:

import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.google.common.base.CaseFormat;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FixJsonPropertyNames {
    public static void main(String[] args) throws IOException {
        Path sourceDir = Paths.get("generated-sources/src/main/java");
        Files.walk(sourceDir)
             .filter(path -> path.toString().endsWith(".java"))
             .forEach(path -> {
                 try {
                     CompilationUnit cu = StaticJavaParser.parse(path.toFile());
                     // 遍历所有@JsonProperty注解
                     cu.findAll(AnnotationExpr.class, a -> "JsonProperty".equals(a.getName().asString()))
                       .forEach(anno -> {
                           if (anno instanceof NormalAnnotationExpr) {
                               NormalAnnotationExpr normalAnno = (NormalAnnotationExpr) anno;
                               normalAnno.getPairs().forEach(pair -> {
                                   if ("value".equals(pair.getName().asString())) {
                                       String original = ((StringLiteralExpr) pair.getValue()).getValue();
                                       // 转换为蛇形命名
                                       String snakeCase = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, original);
                                       pair.setValue(new StringLiteralExpr(snakeCase));
                                   }
                               });
                           }
                       });
                     // 写回修改后的文件
                     Files.write(path, cu.toString().getBytes(StandardCharsets.UTF_8));
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             });
    }
}

内容的提问来源于stack exchange,提问作者ystan-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:37:37