java dto 接受时间参数及响应指定时间格式解决办法

一、yml配置
关键代码:date-format: yyyy-MM-dd HH:mm:ssserverTimezone=UTC

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/auction?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: root

二、dto请求参数配置

关键代码:Timestamp

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;
import java.sql.Timestamp;

/**
 * dto
 *
 * @author qq943
 * @date 2021/05/14 09:35
 **/
@Data
@ApiModel("添加竞拍商品dto")
public class ProductsAddDto {
    @NotNull
    @ApiModelProperty("标题")
    private String title;
    @NotNull
    @ApiModelProperty("开拍时间")
    private Timestamp startTime;
    @NotNull
    @ApiModelProperty("结束时间")
    private Timestamp endTime;
}

三、swagger配置

关键代码:directModelSubstitute(Timestamp.class, String.class)

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enabled)
                .apiInfo(
                        new ApiInfoBuilder()
                                .title(title)
                                .description(title)
                                .termsOfServiceUrl(serverUrl)
                                .version(version)
                                .contact(new Contact(contact_author, contact_url, contact_email))
                                .build()
                )
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                // 将timestamp类型的请求参数以string的类型接收
                .directModelSubstitute(Timestamp.class, String.class)
                ;
    }

四、响应时间戳改为指定格式

    @ApiModelProperty("开拍时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date startTime;
    @ApiModelProperty("结束时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date endTime;

或者统一配置项目所有的

@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
 
    @Override
    protected void configureMessageConverters(List> converters) {
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jacksonConverter.getObjectMapper();
        // 忽略未知属性 
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 设置时间格式(时间格式可以通过配置文件获取,增加灵活度)
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        jacksonConverter.setObjectMapper(objectMapper);
        converters.add(jacksonConverter);
    }
}

你可能感兴趣的:(java dto 接受时间参数及响应指定时间格式解决办法)