正经学徒,佛系记录,不搞事情
正常引入swagger的maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
项目启动后一切正常,但是当访问swagger-ui时,后台报异常了
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.valueOf(Long.java:803)
at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at......
虽然不影响使用,但是看着心烦,断点调试后发现报错来源于swagger-models-1.5.20.jar报里的类AbstractSerializableParameter.java的如下代码
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;
}
}
这里只判断了this.example == null才返回null,其余会去进行转换,而空字符串也会进行转换,导致格式抛出格式化转换异常
解决方法是,换一个swagger-models的版本,这里尝试了一下swagger-models-1.5.22版本的
修改pom文件
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
再来看看相同位置的源码
public Object getExample() {
if (this.example != null && !this.example.isEmpty()) {
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;
} else {
return this.example;
}
}
对example同时进行了null和空值的判断,官方也发现了自己的这个问题,我们进行相应的替换即可