Jackson ObjectMapper in Static Method with Generics

寵の児 提交于 2021-01-29 16:57:21

问题


I have a static method that is intended to read JSON and Parse to a Class (specified at runtime) with ObjectMapper. I would like to return an Object of the 'N' type, but I'm getting an error about using Generics.

How can I make the following code accomplish this?

    public static <N, T extends AbstractRESTApplication> N GET_PAYLOAD( T app, String urlString, REQUEST_TYPE requestType) throws JsonProcessingException, MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
    HttpsURLConnection con = null;
    try {
        RSSFeedParser.disableCertificateValidation();
        URL url = new URL(urlString);
        con = (HttpsURLConnection) url.openConnection();
        String encoding = Base64.getEncoder().encodeToString((app.getUser() + ":" + app.getPassword()).getBytes("UTF-8"));
        con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
        //con.setDoOutput(true);//only used for writing to. 
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(requestType.toString());
        con.setRequestProperty("User-Agent", "Java client");

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        //   wr.write(val);
        StringBuilder content;

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

            String line;
            content = new StringBuilder();

            while ((line = in.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
            System.out.println(Class.class.getName() + ".GET_PAYLOAD= " + content);
            //Map Content to Class.
            ObjectMapper om = new ObjectMapper();
            return om.readValue(content.toString(),N);//Doesn't Like N type. How do i fix?

        }

    } finally {
        con.disconnect();
    }

}

回答1:


Java Generics are implemented using "type erasure". That means the compiler can check the type safety and the types get removed at run time.

So you can't use your type variables ("N") like that. You have to pass the actual class as an argument:

public static <N, T extends AbstractRESTApplication> N GET_PAYLOAD( T app,
    String urlString, REQUEST_TYPE requestType,
    Class<N> nClass) throws ... {

    return om.readValue(content.toString(), nClass);


来源:https://stackoverflow.com/questions/62452365/jackson-objectmapper-in-static-method-with-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!