1、遇到的问题
安装postman后发送请求地址和请求体中,采用 RestFul 风格,修改采用put
Body:
{
"area":"大关",
"openHours":"10:00-22:00",
"sold":4215,
"images":"https://qcloud.dpfile.com/pc/jiclIsCKmOI2arxKN1Uf0Hx3PucIJH8q0QSz-Z8llzcN56-_QiKuOvyio1OOxsRtFoXqu0G3iT2T27qat3WhLVEuLYk00OmSS1IdNpm8K8sG4JN9RIm2mTKcbLtc2o2vfCF2ubeXzk49OsGrXt_KYDCngOyCwZK-s3fqawWswzk.jpg,https://qcloud.dpfile.com/pc/IOf6VX3qaBgFXFVgp75w-KKJmWZjFc8GXDU8g9bQC6YGCpAmG00QbfT4vCCBj7njuzFvxlbkWx5uwqY2qcjixFEuLYk00OmSS1IdNpm8K8sG4JN9RIm2mTKcbLtc2o2vmIU_8ZGOT1OjpJmLxG6urQ.jpg",
"address":"金华路锦昌文华苑29号",
"comments":3035,"avgPrice":80,
"updateTime":1642066339000,
"score":37,
"createTime":1640167839000,
"name":"102茶餐厅",
"x":120.149192,
"y":30.316078,
"typeId":1,
"id":1}
IDEA报错:
2025-05-19 16:19:14.191 ERROR 15912 — [nio-8081-exec-7] com.hmdp.config.WebExceptionAdvice : org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: raw timestamp (1642066339000) not allowed for java.time.LocalDateTime: need additional information such as an offset or time-zone (see class Javadocs); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: raw timestamp (1642066339000) not allowed for java.time.LocalDateTime: need additional information such as an offset or time-zone (see class Javadocs)
at [Source: (PushbackInputStream); line: 8, column: 14] (through reference chain: com.hmdp.entity.Shop[“updateTime”])
原来是Jackson无法将时间戳转换为LocalDateTime 类型数据。
2、修改如下
2.1 pom.xml文件增加配置依赖:
<!--解析前端传来的json 时间戳串 序列化为 LocalDateTime-->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
2.2 增加配置类
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 注册 Java 8 时间模块,支持 LocalDateTime 等
JavaTimeModule module = new JavaTimeModule();
// 添加自定义的 LocalDateTime 反序列化器(把时间戳转为 LocalDateTime)
module.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
// 从 JSON 中读取时间戳(毫秒值)
long timestamp = p.getLongValue();
// 转为 LocalDateTime(使用系统默认时区)
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
}
});
// 注册模块
mapper.registerModule(module);
return mapper;
}
}
2.3 成功效果图