最近在做swagger接口文档时,返回的字段显示不完全,rows集合内的实体类没有任何字段。

如图,rows是返回的实体类集合,这里面没有任何字段。

在查阅了一番文档后,做个总结。


第1步:标注实体类的字段

@ApiModel("ReportPage")
@Data
@TableName("report_page")
public class ReportPage {

    @ApiModelProperty("报表id")
    //报表类型id
    @TableId(value = "page_id",type = IdType.AUTO)
    private Integer pageId;

    @ApiModelProperty("报表名称")
    private String pageName;

.....
}

使用@ApiModel来说明该类是个什么实体,使用@ApiModelProperty来标注字段的含义

第二步:用来统一返回的结果类(例如DataResponse、Result等),需要使用泛型

import java.util.List;

/**
 * 返回的结果类
 */
public class GridBean<T> {

	private int page; //当前页

    ....
	private List<T> rows;//当前页数据
	

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public List<T> getRows() {
		return rows;
	}

	public void setRows(List<T> rows) {
		this.rows = rows;
	}


}

需要使用泛型来声明集合中数据,包括set、get方法,都需要使用T。或者直接使用lombok的@Data注解。

第三步:Controller的返回类也需要使用泛型T

    @ApiOperation(value = "查询报表列表", httpMethod = "POST", notes = "按时间范围分页查询报表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int"),
            @ApiImplicitParam(name = "rows", value = "页大小", required = true, dataType = "int"),
            @ApiImplicitParam(name = "filterDateLeft", value = "开始时间", required = true, dataType = "string"),
            @ApiImplicitParam(name = "filterDateRight", value = "结束时间", required = true, dataType = "string"),
            @ApiImplicitParam(name = "reportKind", value = "报表类型", required = true, dataType = "int"),
            @ApiImplicitParam(name = "envId", value = "租户id", required = true, dataType = "int")
    })
    @ApiVersion(group = ApiVersionConstant.V22)
    @PostMapping(value = "/list")
    public GridBean<ReportPage> list(@RequestBody JSONObject params) {
        PagerModel pagerModel = JSONObject.toJavaObject(params, PagerModel.class);
        ReportPageMo reportPage = JSONObject.toJavaObject(params, ReportPageMo.class);
        return thisService.listPage(reportPage, pagerModel);
    }

为了保险起见,Controller调用的service与serviceImpl,全部使用泛型T。


以上的步骤全部走完之后,swagger就能成功的显示出返回结果类的全部字段了。

值得注意的是:

  • 不推荐接口接收Map、JSONObject、Object类型的参数,这些参数对于swagger来说,是一种未知的数据结构。
  • 只要是统一的返回结果类,或包含可变类型的类,一定要使用泛型T,这是一种规范。
  • 不要直接返回类似Result<Object>的结果,这对于开发人员,或者是swagger来说,依然不是一个很好的选择方案。能够确定Object为User类型,那么直接返回Result<User>。

写在结尾的话:

规范不是压迫或约束,是一种负责。