Java 使用Feign反序列化LocalDateTime
我在尝试反序列化包含LocalDateTime字段的JSON POST响应时遇到异常Java 使用Feign反序列化LocalDateTime,java,date,localdate,spring-cloud-feign,Java,Date,Localdate,Spring Cloud Feign,我在尝试反序列化包含LocalDateTime字段的JSON POST响应时遇到异常 feign.codec.DecodeException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING 以下是JSON格式的响应: { "date":"2018-03-18 01:00:00.000" } 以下是我创建远程服务的方式: @PostConstruct void createService() {
feign.codec.DecodeException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
以下是JSON格式的响应:
{
"date":"2018-03-18 01:00:00.000"
}
以下是我创建远程服务的方式:
@PostConstruct
void createService() {
remoteService = Feign.builder()
.decoder(new GsonDecoder())
.encoder(new GsonEncoder())
.target(RemoteInterface.class, remoteUrl);
}
如何强制Faign将日期反序列化为LocalDateFormat?我通过使用自定义类型适配器创建自己的
GsonDecoder
解决了这个问题:
public class CustomGsonDecoder extends GsonDecoder {
public CustomGsonDecoder(){
super(new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), dtf);
}
}).registerTypeAdapter(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
return new JsonPrimitive(dtf.format(localDateTime));
}
}).create());
}
}
public类CustomGsonDecoder扩展GsonDecoder{
公共CustomGsonDecoder(){
超级(新的GsonBuilder()
.registerTypeAdapter(LocalDateTime.class,新的JsonDeserializer()){
@凌驾
公共LocalDateTime反序列化(JsonElement json,类型,JsonDeserializationContext JsonDeserializationContext)引发JsonParseException{
DateTimeFormatter dtf=模式的DateTimeFormatter.of(“yyyy-MM-dd HH:MM:ss.SSS”);
返回LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(),dtf);
}
}).registerTypeAdapter(LocalDateTime.class,新的JsonSerializer()){
@凌驾
公共JsonElement序列化(LocalDateTime LocalDateTime,类型,JsonSerializationContext JsonSerializationContext){
DateTimeFormatter dtf=模式的DateTimeFormatter.of(“yyyy-MM-dd HH:MM:ss.SSS”)
返回新的JsonPrimitive(dtf.format(localDateTime));
}
}).create());
}
}
您如何对其进行反序列化,请向我们展示您的代码好吗?@YCF\u L,谢谢您的评论。我已经更新了我的帖子。很好。感谢分享您的解决方案。您可以在类中只声明一个静态日期时间格式化程序,而不是每次实例化一个。它是线程安全的,所以即使并行处理多个响应,也不应该造成问题。