Spring Boot中使用ObjectMapper格式化RabbitMQ JSON的Time字段方法
在Spring Boot中处理RabbitMQ传来的.NET风格日期格式
我来帮你搞定这个问题!你拿到的/Date(1584260162000)/是典型的旧.NET框架生成的JSON日期格式,在Spring Boot里用Jackson的ObjectMapper处理它有几种实用方案,我给你详细拆解:
方案一:自定义Jackson反序列化器(最灵活)
这种方法可以精准适配这种特殊日期格式,适用于单个或多个实体类的场景。
1. 定义消息实体类
先创建对应RabbitMQ消息的实体类,推荐用Java 8+的LocalDateTime替代Date,更符合现代Java开发规范:
public class RabbitMqVehicleMessage { private String PlateNo; private String DeviceId; private LocalDateTime Time; private Double Latitude; private Double Longitude; private String Address; private Integer GPSSpeed; private Boolean IsValid; // 生成全参/无参构造器、getter和setter方法 }
2. 编写自定义反序列化器
专门处理/Date(时间戳)/格式的反序列化逻辑:
public class DotNetLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> { // 匹配.NET日期格式的正则表达式 private static final Pattern DOT_NET_DATE_PATTERN = Pattern.compile("/Date\\((\\d+)\\)/"); public DotNetLocalDateTimeDeserializer() { this(null); } public DotNetLocalDateTimeDeserializer(Class<?> vc) { super(vc); } @Override public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { String dateStr = parser.getText(); Matcher matcher = DOT_NET_DATE_PATTERN.matcher(dateStr); if (matcher.find()) { // 提取时间戳并转换为LocalDateTime long timestamp = Long.parseLong(matcher.group(1)); return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()); } throw new IOException("无法解析.NET风格日期:" + dateStr); } }
3. 注册反序列化器
有两种注册方式,根据你的场景选择:
- 局部生效(单个实体类):在
Time字段上添加@JsonDeserialize注解,指定使用我们的自定义反序列化器;如果需要序列化时输出友好格式,再搭配@JsonFormat:@JsonDeserialize(using = DotNetLocalDateTimeDeserializer.class) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Dubai") private LocalDateTime Time; - 全局生效(所有实体类):在Spring Boot配置类中全局配置
ObjectMapper,让所有LocalDateTime类型的字段都能处理这种格式:@Configuration public class JacksonGlobalConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule customModule = new SimpleModule(); customModule.addDeserializer(LocalDateTime.class, new DotNetLocalDateTimeDeserializer()); objectMapper.registerModule(customModule); // 全局配置序列化日期格式,避免输出时间戳 objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return objectMapper; } }
额外提示
- 如果你的字段必须用
Date类型,只需把反序列化器的泛型改成Date,返回new Date(timestamp)即可。 - 时区配置要和业务场景匹配,示例中用了迪拜时区(
Asia/Dubai),你可以根据需求调整为UTC或其他时区。
内容的提问来源于stack exchange,提问作者Fazlan Ahamed
相关产品推荐
相关产品推荐

