使用Feign反序列化LocalDateTime

5

当尝试反序列化包含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() {
    remoteService = Feign.builder()
            .decoder(new GsonDecoder())
            .encoder(new GsonEncoder())
            .target(RemoteInterface.class, remoteUrl);
}

我该如何强制Feign将日期反序列化为LocalDateFormat?

你是如何反序列化它的?能否展示一下你的代码? - Youcef LAIDANI
@YCF_L,感谢您的评论。我已经更新了我的帖子。 - kstanisz
1个回答

5

我通过创建自己的 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());
    }
}

1
不错。感谢分享你的解决方案。你可以在类中声明一个静态日期时间格式化程序,而不是每次实例化一个。它是线程安全的,因此即使多个响应并行处理也不会出现问题。 - Ole V.V.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接