Spring Boot 2.7.7控制器返回Date变为毫秒时间戳问题求助
解决Spring Boot 2.7.7控制器直接返回Date类型时输出时间戳的问题
问题原因
当控制器方法直接返回Date类型时,Spring MVC会优先使用内置的Converter处理响应,而非Jackson的序列化器,导致你配置的spring.jackson.serialization.write-dates-as-timestamps=false和@JsonFormat注解失效。但返回包含Date属性的JSON对象时,会触发Jackson的序列化逻辑,所以日期格式正常。
解决方法
方法1:将Date包装为DTO返回
把单独的Date包装进一个简单的DTO类,让Spring使用Jackson序列化:
// 定义DTO类 public class DateResult { private Date date; public DateResult(Date date) { this.date = date; } public Date getDate() { return date; } } // 修改控制器方法 @PostMapping("stbClobil") public DateResult getClobil( @RequestParam(name = "idBilan") Integer idBilan, @RequestParam(name = "idDomaine") Integer idDomaine) { Date maxClobil = this.stbService.getMaxClobil(idBilan, idDomaine); return new DateResult(maxClobil); }
方法2:自定义Date转String的Converter
注册一个自定义Converter,让Spring直接把Date转为指定格式的字符串:
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class DateToStringConverter implements Converter<Date, String> { // 匹配目标格式:2022-01-30T23:00:00.000+00:00 private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @Override public String convert(Date source) { return formatter.format(source); } }
方法3:手动用ObjectMapper序列化
注入Spring容器中的ObjectMapper,手动将Date序列化为JSON字符串:
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Date; @PostMapping("stbClobil") public String getClobil( @RequestParam(name = "idBilan") Integer idBilan, @RequestParam(name = "idDomaine") Integer idDomaine) throws Exception { Date maxClobil = this.stbService.getMaxClobil(idBilan, idDomaine); return objectMapper.writeValueAsString(maxClobil); }
内容的提问来源于stack exchange,提问作者Jeanne Lauwers
相关产品推荐
相关产品推荐

