将 JSON 反序列化为动态加载的 class 文件

deserialize JSON into dymanically loaded class file

我已经在 JSON 响应中从 Schema 生成了 POJO,编译并加载了从 POJO 生成的 class 但是在反序列化 JSON 响应时我没有我可以反序列化的实际 class。

MyClassLoader classLoader = new MyClassLoader(POJOGeneratorForJSON.class.getClassLoader());

Class parentJsonClass = classLoader.loadClass(topLevelclassName, classpathLoc);

ObjectMapper mapper = new ObjectMapper();

byte[] jsonBytes = generator.getBytesFromURL(source);

if(jsonBytes != null){

    Object jsonObj = parentJsonClass.newInstance();
    jsonObj = mapper.readValue(jsonBytes, Class.class);
}

我得到的异常是:"com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Class out of START_OBJECT token"

我知道在 mapper.readValue() 中我需要提供实际的 class 作为第二个参数,但不知道如何。有人可以帮我解决吗?

readValue 的第二个参数上,您需要传递一个 Class 实例来定义您要读取的对象的类型。您似乎正在传递 Class 本身的类型。而且 jackson 无法从 jsonBytes 中反序列化 Class 对象。这样的事情应该有效:

Object jsonObj = mapper.readValue(jsonBytes, parentJsonClass);

即从 jsonBytes

中读取 parentJsonClass 类型的对象