Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic polymorphic type handling with Jackson

Tags:

java

json

jackson

I have a class hierarchy similar to this one:

public static class BaseConfiguration {
}

public abstract class Base {
  private BaseConfiguration configuration;
  public String id;

  public BaseConfiguration getConfiguration() { ... }
  public void setConfiguration(BaseConfiguration configuration) { ... }
}

public class A extends Base {
   public static class CustomConfigurationA extends BaseConfiguration {
       String filename;
       String encoding;
   }

   CustomConfigurationA getConfiguration() { ... }
}

class B extends Base {
   public static class CustomConfigurationB extends BaseConfiguration {
       /* ... */
   }

   CustomConfigurationB getConfiguration() { ... }
}

And json input like this one (which I cannot change myself)

{
    "id":"File1",
    "configuration":{
         "filename":"...",
         "encoding":"UTF-8"
     }
}

I am parsing the JSON in Java with Jackson like this

ObjectMapper mapper = new ObjectMapper();
value = mapper.readValue(in, nodeType);

I want to deserialize classes A, B and others from JSON using JAVA/Jackson. There are no type information embedded in JSON (and can't be). I can't use annotations on the classes (I don't own them) and I (believe) I can't use mixins since there are potentially arbitrary numbers of classes like A & B (and mixins are not dynamic). Good thing is that the deserializing code knows which is the correct custom class to use for deserializing (basically there is a known mapping from class to configuration class), but I do not know how make Jackson recognize this information when deserializing the JSON.

In short: I want to be able to resolve the deserialization type of the configuration object depending on the surrounding class type by setting whatever is necessary on ObjectMapper. How can this be achieved?

like image 209
adriano Avatar asked Nov 21 '11 10:11

adriano


1 Answers

Apparently the answer was to implement something similar to the sixth solution posted at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html, which uses unique JSON element names to identify the target type to deserialize to.

like image 131
Programmer Bruce Avatar answered Oct 29 '22 10:10

Programmer Bruce