dermoritz
dermoritz

Reputation: 12991

Jackson deserialize polymorphic types not under my control

I want to (un)marshal an Object that contains a field of this type. While the serialization works well i am not able to deserialize it. The implementing classes are not under my control. I guess in general it is not possible to deserialize to the original implementing class due to missing constructors and or setters.

On the other hand i want to save all information (as java object) contained in the json.

What are my options to achieve this, are there best or good practices?

Upvotes: 1

Views: 582

Answers (1)

ST-DDT
ST-DDT

Reputation: 2707

You could use Jackson Mixins to fake a @JsonDeserialize(using=CustomDeserializer.class) annotation on the class/field in question. Then you can try to create the instances yourself in the given deserializer class.

// I'm not sure whether annotations (@JsonTypeInfo) on class level are supported as well to allow the polymorphistic type decision.
abstract class MixIn {

  // make constructor usable if available
  MixIn(@JsonProperty("id") int a, @JsonProperty("name") String b) { }

  @JsonDeserialize(using=CustomDeserializer.class) abstract TypeX getTypeX();
  
}

And then you can use it like this

objectMapper.addMixIn(TypeXContainer.class, MixIn.class);

Doks: http://wiki.fasterxml.com/JacksonMixInAnnotations

Upvotes: 2

Related Questions