使用Feign反序列化LocalDateTime

时间:2018-04-09 11:43:16

标签: 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() {
    remoteService = Feign.builder()
            .decoder(new GsonDecoder())
            .encoder(new GsonEncoder())
            .target(RemoteInterface.class, remoteUrl);
}

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

1 个答案:

答案 0 :(得分:1)

我通过使用自定义类型适配器创建自己的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());
    }
}