springboot LocalDateTime json响应多一个T
时间: 2025-01-18 14:45:12 浏览: 37
### 解决 Spring Boot 中 LocalDateTime 序列化为 JSON 时去除 'T'
为了使 `LocalDateTime` 类型在序列化成 JSON 字符串时不带 'T' 符号,可以通过自定义 Jackson 的序列化器来实现这一点。默认情况下,Jackson 使用 ISO-8601 格式进行日期时间的序列化,在这种格式下,日期时间和时间之间会有一个大写的 'T'。
#### 方法一:全局配置
通过创建一个配置类并注册 `JavaTimeModule` 和自定义的 `ObjectMapper` 来调整整个应用程序的行为:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
return mapper;
}
}
```
此方法适用于希望在整个项目范围内改变 `LocalDateTime` 输出格式的情况[^1]。
#### 方法二:局部字段级定制
如果只需要针对特定实体属性做特殊处理,则可以在该字段上加注解指定格式:
```java
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
public class Event {
private int id;
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime time;
// getters and setters...
}
```
这种方式更加灵活,允许不同对象有不同的表现形式。
另外需要注意的是,当遇到类似 `InvalidDefinitionException` 这样的错误提示时,说明当前环境缺少必要的模块支持,因此还需要确保已经添加了依赖项 `jackson-datatype-jsr310` 到项目的构建文件中,以便能够正确解析和生成 Java 8 新增的时间类型数据。
阅读全文
相关推荐

















