Swagger报错:Illegal DefaultValue null for parameter type number

报错信息

今天启动项目打开 Swagger 文档的时候,突然报了这么个错误:

1
2
3
i.s.m.p.AbstractSerializableParameter : Illegal DefaultValue null for parameter type number
java.lang.NumberFormatException: empty String
......

或者像这样:

1
2
3
i.s.m.p.AbstractSerializableParameter : Illegal DefaultValue null for parameter type integer
java.lang.NumberFormatException: For input string: ""
...

然而程序运行一切正常,检查代码也没发现什么错误,最后锁定到了 Swagger 身上。

报错原因

原因出自日志中的这一句:

1
at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]

点进入看看源码io.swagger.models.parameters.AbstractSerializableParameter#getExample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@JsonProperty("x-example")
public Object getExample() {
if (this.example == null) {
return null;
} else {
try {
if ("integer".equals(this.type)) {
return Long.valueOf(this.example);
}

if ("number".equals(this.type)) {
return Double.valueOf(this.example);
}

if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
return Boolean.valueOf(this.example);
}
} catch (NumberFormatException var2) {
LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
}

return this.example;
}
}

这下就明白了,因为是 Swagger 文档工具报的异常,所以程序正常运行丝毫没有影响。文档的使用好像也没问题,至少我没遇到。完全可以忽略这个问题,不过作为强迫症,每次启动程序都要看这个异常属实有点不爽,必须解决掉!

解决方法

方法一:把 @ApiModelPropertyexample 属性填上

像这样:

1
2
@ApiModelProperty(value = "id", example = "0")
private Integer id;

但是类如果比较多的话,一个个去改有点难顶,有没有什么简捷点的方法呢?

不想偷懒的程序员不是好程序员。

方法二:升级依赖

我使用的 Swagger 版本是 io.springfox.springfox-swagger2: 2.9.2,其中 swagger-models 的版本是 1.5.20,将其升到 1.5.21 即可。如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>

刷新 Maven 依赖,重启项目,再打开 Swagger 文档,没有异常报告,问题完美解决。

曾梦想仗剑走天涯,后来没钱就没去