简体   繁体   English

Jackson ObjectMapper 在 Static 方法与 Generics

[英]Jackson ObjectMapper in Static Method with Generics

I have a static method that is intended to read JSON and Parse to a Class (specified at runtime) with ObjectMapper.我有一个 static 方法,旨在读取 JSON 并使用 ObjectMapper 解析为 Class(在运行时指定)。 I would like to return an Object of the 'N' type, but I'm getting an error about using Generics.我想返回一个“N”类型的 Object,但在使用 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();
    }

}

Java Generics are implemented using "type erasure". Java Generics 是使用“类型擦除”实现的。 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.所以你不能像那样使用你的类型变量(“N”)。 You have to pass the actual class as an argument:您必须将实际的 class 作为参数传递:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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