我有一个RestEasyClient,它必须对一个内部有java.time.Instant的对象进行反序列化。试图从jsr310注册新的JavaTimeModule但仍然有错误:
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
ResteasyClient client = new ResteasyClientBuilder()
.register(mapper)
.build();
ResteasyWebTarget target = client.target(UriBuilder.fromPath(SERVICE_URL + "/api"));
错误:
无法构造java.time.Instant的实例:找不到合适的构造函数,无法从Object值反序列化(缺少默认构造函数或创建者,或者可能需要添加/启用类型信息?)
修改Rest Server以正确序列化Instant类(例如:“fromTime”:1525681860)
新错误:
无法构造java.time.Instant的实例:没有double / Double-argument构造函数/工厂方法从Number值反序列化(1.52568186E9)
我设法模拟了这个:
ObjectMapper deserializer = new ObjectMapper()
.registerModule(new JavaTimeModule());
Instant probe = deserializer.readValue("1525681860", Instant.class);
System.out.println(probe);
如果我删除“registerModule”行,我会复制相同的错误。
因此,结论是ResteasyClient没有注册模块。我肯定做错了。
答案 0 :(得分:1)
您可以为ContextResolver
定义ObjectMapper
:
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
}
然后在客户端实例中注册解析器:
ResteasyClient client = new ResteasyClientBuilder()
.register(ObjectMapperContextResolver.class).build();
或者,您可以注册JacksonJsonProvider
的实例。此类是JAX-RS抽象(MessageBodyReader
和MessageBodyWriter
)的基本实现,用于将JSON内容与Java对象绑定和从Java对象绑定。
您可以使用接受constructor实例的ObjectMapper
。