当我试图反序列化包含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?
发布于 2018-04-09 21:08:09
我已经通过创建自己的带有自定义类型适配器的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());
}
}https://stackoverflow.com/questions/49732135
复制相似问题