快捷搜索: 王者荣耀 脱发

Swagger(或Postman)关于日期类型的传参方式

前言:调试接口经常用到Swagger或者Postman,但每每遇到日期类型很容易出现问题。

post请求可能会报如下异常:

Can not deserialize value of type java.util.Date from String "2020-08-01 00:00:00": not a valid representation (error: Failed to parse Date value 2020-08-01 00:00:00: Can not parse date "2020-08-01 00:00:00Z": while it seems to fit format yyyy-MM-ddTHH:mm:ss.SSSZ, parsing fails (leniency? null))

get请求可能会报如下异常:

Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @io.swagger.annotations.ApiParam java.util.Date] for value 2020-08-12T06:25:39.929Z; nested exception is java.lang.IllegalArgumentException

总而言之都是因为JAVA代码中接受日期的字段识别不了调试工具传过来的日期类型,下面我们就来解决该问题。

一.post请求

解决方式-1

直接按照swagger提示的类型传入,swagger默认的日期格式如下:

但这种方式需要注意,这里的时间是标准的 XML Schema的"日期型数据格式”,T是代表后面跟着“时间”。Z代表0时区,或者叫UTC统一时间(UTC通用标准时)。所以假如你想接收到你想要的时间,就要按照这个格式减去8小时。例如你想得到的时间为2020-08-12 12:10:50,则你需要传过来的时间为2020-08-12T04:10:50.000Z。

参考:

解决方式-2

如果觉得解决方式-1这种方式的时间格式太麻烦,可以设置JAVA代码中接受日期的字段,设置成自己习惯的时间格式。

设置代码如下(在字段上添加@JsonFormat注解):

public class AttendanceResultStatisticsQryParam {

    @ApiModelProperty(required = true,example = "1997-01-01 00:00:00",value = "日期")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date time;

}

设置后就可以按照yyyy-MM-dd HH:mm:ss这种时间格式输入时间了,如下:

解决方式-3

参考:

二.get请求

get请求的日期类型参数比较简单,在Swagger和Postman时间格式为:2020/08/12 00:00:00。

参考:

经验分享 程序员 微信小程序 职场和发展