【发布时间】:2017-11-08 05:34:55
【问题描述】:
我正在为响应看起来像这样的 Web 服务编写客户端:
{
"succeed": true,
"code": 2000,
"pagination": {
"items": [
{
"id": 17694,
...
},
{
"id": 17695,
...
}
],
"count": 2,
"offset": 0
},
"message": "Petición satisfactoria."
}
响应总是每个请求返回一个类型的列表,我的问题是 items 数组可以是不同的类型,例如:
{
"id", 1,
"otherProperty" : "Foo",
...
}
或
{
"id", 1,
"anotherProperty" : "Foo",
...
}
我尝试将该响应映射到一个 Java 类,例如:
public class WsResponse {
private WsPagination<?> pagination;
private boolean succeed;
...
}
WsPagination 的位置:
public class WsPagination <T> {
List<T> items;
int count;
int offset;
...
}
它可以工作,但是 items 列表作为 java.util.LinkedHashMap 返回,我希望 RestEasyClient 序列化为正确的类
例子:
public class Foo {
Long id;
String otherProperty;
}
还有
public class Bar {
Long id;
String anotherProperty;
}
我尝试为 WsPagination 类型注册一个自定义 JsonDeserializer 但它没有被调用,不知道为什么。
Class<?> clazz = getRequestType();
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("myModule",
new Version(1, 0, 0, "", "", ""));
module.addDeserializer(WsPagination.class, new WsPaginationDeserializer(clazz));
mapper.registerModule(module);
ResteasyClient client = new ResteasyClientBuilder()
.register(module)
.register(new ClientRequestFilter() {
@Override
public void filter(ClientRequestContext context)
throws IOException {
for (Map.Entry<String, String> entrySet : headers
.entrySet()) {
String key = entrySet.getKey();
String value = entrySet.getValue();
context.getHeaders().add(key, value);
}
}
}).build();
WsPaginationDeserializer 类:
public class WsPaginationDeserializer extends JsonDeserializer<WsPagination> {
Class<?> clazz;
/**
* Constructs a new instance of type FooTest.WsPaginationDeserializer
*/
public WsPaginationDeserializer(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public WsPagination deserialize(JsonParser arg0,
DeserializationContext arg1)
throws IOException, JsonProcessingException {
// method not called
throw new IOException("Deserialize here!!");
}
}
我怎样才能得到以正确类型填充的项目列表。
谢谢。
编辑 2017 年 11 月 14 日
作为一项工作,获取这些 java.util.LinkedHashMap 并将它们转换为相应的模型:
if(path.equals("somePath")){
if((result = resp.getResult()) != null){
Object items = null;
if((items = result.getItems()) != null){
// here items are a list of java.util.LinkedHashMap, so then try to convert them to the model we need for the "somePath"
List models = mapper.convertValue(items, new TypeReference<List<WsComprobante>>() {});
// now re assing the list of WsComprobante again to the result list of items
result.setItems(models);
}
}
}
希望这对某人有所帮助。
【问题讨论】:
标签: web-services resteasy jackson2