如何使用 ObjectMapper Jackson 反序列化泛型

How to deserialize a generic type with ObjectMapper Jackson

我正在努力简化我的代码。我有一个常见的问题,即向 API 发出请求并获得 JSON 对象。这个json可以是CategoriesProducts等,我用的是jacksonObjectMapper.

目前我对每个请求都有一个方法,但我想在一个方法中简化它。例如。

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 中,如图 here 所示,但出现错误 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;
}