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

时间:2015-03-06 08:44:33

标签: java json jackson deserialization fasterxml

我正在努力简化我的代码。我有一个常见的操作,它向API发出请求并获取JSON对象。此json可以是CategoriesProducts等。我使用的是杰克逊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方法添加为方法,如here所示,但我收到错误Cannot find symbol T

1 个答案:

答案 0 :(得分:1)

我终于提出了一个解决方案,就是:

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;
}