RestEasy+Jackson 2自定义反序列化



我正在为Web服务编写一个客户端,其响应看起来像:

{
"succeed": true,
"code": 2000,
"pagination": {
"items": [
{
"id": 17694,
...
},
{
"id": 17695,
...
}
],
"count": 2,
"offset": 0
},
"message": "Petición satisfactoria."
}

响应总是为每个请求返回一个类型的列表,我的问题是数组可以是不同的类型,例如:

{
"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;
...
}

它是有效的,但项的列表返回为java.util.LinkedHashMap,我希望RestEasyClient序列化为正确的类

示例:

public class Foo {
Long id;
String otherProperty;
}

public class Bar {
Long id;
String anotherProperty;
}

我试图为WsPagiation类型注册一个自定义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();

WsPagiationDeserializer类:

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!!");
}

}

我如何才能用正确的类型填写项目列表。

谢谢。

编辑14/11/2017

作为一项工作,获取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);
}
}
}

希望这对某人有所帮助。

您的问题是jackson不知道在反序列化项目时应该使用哪个类。

防止这种情况的一种方法是为每个项目类型创建一个自定义的WSResponse类:

public class WsResponse<T> {
private WsPagination<T> pagination;
private boolean succeed;
...
}
public class WsPagination <T> {
List<T> items;
int count;
int offset;
...
}
public class FooResponse extends WsResponse<Foo>{}
public class BarResponse extends WSResponse<Bar>{}

最新更新