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

如何在Swagger中为ApiModelProperty设置POJO的默认JSON示例

解决方案

方案1:针对Springfox Swagger2 场景

你只需要修改content字段的@ApiModelProperty注解,增加dataType = "Object"参数强制Swagger不递归解析JobConfig的结构,直接使用你填写的示例:

public class CreateConfigRequest {
    @ApiModelProperty(example = "hive")
    String entityType;
    @ApiModelProperty(example = "imports")
    String entityNamespace;
    @ApiModelProperty(example = "hotel")
    String entityName;
    // 新增dataType参数
    @ApiModelProperty(
        example = "{\"name\": \"hotel\", \"batch\": {\"type\": \"FullScan\"}}",
        dataType = "Object"
    )
    JobConfig content;
}

如果希望所有用到JobConfig的地方都复用同一个示例,也可以直接在JobConfig类上添加注解:

@Data
@ApiModel(example = "{\"name\": \"hotel\", \"batch\": {\"type\": \"FullScan\"}}")
public class JobConfig {
    @NonNull private String name;
    @NonNull private BatchSpec batch;
    private ProfileConfig profile;
    private ValidateConfig validate;
    private ActionConfig action;
}

方案2:针对Springdoc OpenAPI3(Swagger3)场景

@ApiModelProperty是Swagger2的原生注解,在OpenAPI3规范下建议使用@Schema注解,直接填写示例即可生效:

import io.swagger.v3.oas.annotations.media.Schema;

public class CreateConfigRequest {
    @Schema(example = "hive")
    String entityType;
    @Schema(example = "imports")
    String entityNamespace;
    @Schema(example = "hotel")
    String entityName;
    @Schema(example = "{\"name\": \"hotel\", \"batch\": {\"type\": \"FullScan\"}}")
    JobConfig content;
}

同样也可以在JobConfig类上全局配置示例:

@Data
@Schema(example = "{\"name\": \"hotel\", \"batch\": {\"type\": \"FullScan\"}}")
public class JobConfig {
    @NonNull private String name;
    @NonNull private BatchSpec batch;
    private ProfileConfig profile;
    private ValidateConfig validate;
    private ActionConfig action;
}

额外优化建议

如果你的项目使用Java15及以上版本,可以用文本块写JSON示例,无需转义双引号,可读性更高:

@Schema(example = """
{
  "name": "hotel",
  "batch": {
    "type": "FullScan"
  }
}
""")
JobConfig content;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:57:00