Swagger2异常:java.lang.NumberFormatException:For input string:""

版权声明:如有问题,欢迎指正。 转载请注明原创地址: https://blog.csdn.net/lilyssh/article/details/82944507

项目源码地址 :https://gitee.com/lilyssh/high-concurrency

1. 异常描述

在访问swagger首页时

报错:

2018-10-05 14:45:13.537  WARN 19699 --- [nio-1111-exec-4] i.s.m.p.AbstractSerializableParameter    : Illegal DefaultValue null for parameter type integer

java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_171]
	at java.lang.Long.parseLong(Long.java:601) ~[na:1.8.0_171]
	at java.lang.Long.valueOf(Long.java:803) ~[na:1.8.0_171]
	at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]
	at sun.reflect.GeneratedMethodAccessor109.invoke(Unknown Source) ~[na:na]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
	at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:687) [jackson-databind-2.9.6.jar:2.9.6]

实体类是这么写的:

package cn.lilyssh.order.api.model.request;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import lombok.Data;
import java.io.Serializable;

@Data
@ApiModel(description = "订单查询请求数据")
public class OrderQueryReq implements Serializable {
    @ApiModelProperty(value = "订单ID")
    private Integer id;
}

2. 异常分析

Illegal DefaultValue null for parameter type integer`和`NumberFormatException: For input string: ""

从上面这句可以看出,有个默认值是空字符串的变量转换成Integer类型时异常。

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

根据上面这句报错信息,点进去AbstractSerializableParameter.java:412可以看到

if (BaseIntegerProperty.TYPE.equals(type)) {
	return Long.valueOf(example);
}

就是说如果实体属性类型是Integer,就把example转为Long类型,而example默认为"",导致转换错误。

3. 解决办法

实体类中,Integer类型的属性加@ApiModelProperty时,必须要给example参数赋值,且值必须为数字类型。

package cn.lilyssh.order.api.model.request;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import lombok.Data;
import java.io.Serializable;

@Data
@ApiModel(description = "订单查询请求数据")
public class OrderQueryReq implements Serializable {
    @ApiModelProperty(value = "订单ID",example = "123")
    private Integer id;
}

大功告成!

展开阅读全文

没有更多推荐了,返回首页