Search code examples
javajsonreflectionjacksonclassloader

deserialize JSON into dymanically loaded class file


I have generated POJO's from Schema in JSON response, compiled and loaded the class generated from POJO's but at the time of deserialization of JSON response I don't have the actual class to which I can deserialize.

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

Exception I am getting is:"com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Class out of START_OBJECT token"

I know that in the mapper.readValue() I need to provide the actual class as second argument, but dont know how. Can someone help me with a workaround?


Solution

  • On the second argument to readValue you need to pass a Class instance defining the type of the object you want to read. It seems you are passing the type of Class itself. And jackson can't deserialize a Class object from jsonBytes. Something like this should work:

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

    i.e. read an object of type parentJsonClass from jsonBytes