反序列化通用类变量

反序列化通用类变量

本文介绍了Jackson - 反序列化通用类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我错误地发布了问题.我在这里正确地发布了问题......

I had posted the question wrongly. I am posting the question correctly here ...

我收到一个 json 字符串作为 HTTP 响应.我知道它的结构.如下:

I am getting a json string as a HTTP response. I know the structure of it. It is as follows:

public class Json<T> {
    public Hits<T> hits;
}
public class Hits<T> {
    public int found;
    public int start;
    public ArrayList<Hit<T>> hit;
}
public class Hit<T> {
    public String id;
    public Class<T> data;
}

数据"字段可以属于任何类.我只会在运行时知道它.我将其作为参数获取.这就是我反序列化的方式.

The "data" field can belong to any class. I will know it at runtime only. I will get it as a parameter. This is how I am deserializing.

public <T> void deSerialize(Class<T> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.readValue(jsonString,  new TypeReference<Json<T>>() {});
}

但我收到一个错误 -

But I am getting an error -

无法从 java.lang.class 访问私有 java.lang.class.Class().无法设置访问权限.无法使 java.lang.Class 构造函数可访问

cannot access private java.lang.class.Class() from java.lang.class. Failed to set access. Cannot make a java.lang.Class constructor accessible

推荐答案

如果泛型类型仅动态可用,您将需要显式构建 JavaType:

You will need to build JavaType explicitly, if generic type is only dynamically available:

// do NOT create new ObjectMapper per each request!
final ObjectMapper mapper = new ObjectMapper();

public Json<T> void deSerialize(Class<T> clazz, InputStream json) {
    return mapper.readValue(json,
      mapper.getTypeFactory().constructParametricType(Json.class, clazz));
}

这篇关于Jackson - 反序列化通用类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:39