Feign反序列化LocalDateTime遇解码异常:Expected BEGIN_OBJECT but was STRING
解决方案:Feign + Gson 反序列化 LocalDateTime 字段异常
这个问题我碰到过,本质是Gson默认没有对Java 8的LocalDateTime类型提供序列化/反序列化支持:你的JSON响应里date字段是字符串格式("2018-03-18 01:00:00.000"),但默认的Gson实例会把LocalDateTime当成一个嵌套对象来解析(期望BEGIN_OBJECT),两者不匹配就抛出了异常。
下面给你两种可行的解决方法:
方法一:全局配置Gson实例,注册LocalDateTime适配器
你需要自定义一个Gson实例,给LocalDateTime类型绑定对应的字符串解析/格式化逻辑,再把这个实例传给Feign的GsonDecoder和GsonEncoder。
步骤1:编写LocalDateTime的TypeAdapter
创建一个适配器类,指定日期字符串的格式(和你的JSON响应格式一致):
import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeAdapter extends TypeAdapter<LocalDateTime> { // 匹配你的JSON日期格式:yyyy-MM-dd HH:mm:ss.SSS private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); @Override public void write(JsonWriter out, LocalDateTime value) throws IOException { // 序列化:把LocalDateTime转成指定格式的字符串 out.value(DATE_FORMATTER.format(value)); } @Override public LocalDateTime read(JsonReader in) throws IOException { // 反序列化:把字符串转成LocalDateTime return LocalDateTime.parse(in.nextString(), DATE_FORMATTER); } }
步骤2:修改Feign服务创建代码
在createService方法里,用GsonBuilder创建带适配器的Gson实例,替换默认的GsonDecoder/GsonEncoder:
@PostConstruct void createService() { // 构建自定义Gson实例,注册LocalDateTime适配器 Gson customGson = new GsonBuilder() .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()) .create(); remoteService = Feign.builder() .decoder(new GsonDecoder(customGson)) // 使用自定义Gson .encoder(new GsonEncoder(customGson)) .target(RemoteInterface.class, remoteUrl); }
方法二:在实体类字段上单独指定适配器
如果你不想全局配置Gson,可以在包含LocalDateTime字段的实体类上,用@JsonAdapter注解指定适配器:
import com.google.gson.annotations.JsonAdapter; import java.time.LocalDateTime; public class YourResponseEntity { // 给date字段绑定自定义适配器 @JsonAdapter(LocalDateTimeAdapter.class) private LocalDateTime date; // 省略getter、setter方法 }
这种方式更灵活,只对特定字段生效,不需要修改Feign的全局配置。
内容的提问来源于stack exchange,提问作者kstanisz
相关产品推荐
相关产品推荐

