简体   繁体   中英

How to deserialize a generic type with ObjectMapper Jackson

I am struggling trying to simplify my code. I have a common oppperation that makes a request to an API and gets a JSON object. This json can be Categories , Products etc. I am using jackson ObjectMapper .

Currently I have a method for each request, but I want to simplify it in one method. For example.

myMethod(String Path, Here The class Type)

One of this common methods is:

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

The one thing that changes across all methods is the type of object to retrieve.

It is possible to generalize the line

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });

To be

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
        });

I've tried to add as a param to the method Class<T> class , as shown here , but I get the error Cannot find symbol T

I finally came up with a solution, here it is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM