[英]How to deserialize a generic type with ObjectMapper Jackson
我正在努力尝试简化我的代码。 我有一个常见的操作,它向API发出请求并获取JSON对象。 这个json
可以是Categories
, Products
等。我使用的是jackson ObjectMapper
。
目前我有一个方法用于每个请求,但我想在一个方法中简化它。 例如。
myMethod(String Path, Here The class Type)
其中一种常见方法是:
public List<Category> showCategories() {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(Constants.GET_CATEGORY);
getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());
List<Category> data = null;
HttpResponse response;
try {
response = client.execute(getRequest);
data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
});
} catch (IOException ex) {
LOGGER.error("Error retrieving categories, " + ex.toString());
}
// TODO: Replace List<category> with Observable?
return data;
}
在所有方法中改变的一件事是要检索的对象的类型。
可以概括该线
Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
});
成为
Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
});
我试图添加为参数去的方法Class<T> class
,如这里 ,但我得到的错误Cannot find symbol T
我终于想出了一个解决方案,这里是:
public static <T> List<T> getList(String url, Class<T> clazz) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(url);
getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());
List<T> data = null;
HttpResponse response;
try {
response = client.execute(getRequest);
data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), Constants.JSON_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException ex) {
logger.error("Error retrieving " + clazz.getName() + " " + ex.toString());
}
// TODO: Replace List<category> with Observable?
return data;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.