'Deserializing Java class with incomplete ParameterTyped properties - Jackson

Consider we are having the following classes

//following classes are present in external lib, we can not modify them.
class A{
  private Map mapOfListOfB; // this should have been properly typed Map<String,List<B>>
}

class B{
  private int val1;
  private String val2;
  private C val3; // Class C can be anything but the point here is the same object of C can be used in multiple B objects
//which means we can reuse the reference using @JsonIdentityInfo
}

now, when we use Jackson's objectMapper to serialize and deserialize this Class A, we would not be able to deserialize because we are not giving any typed info to Jackson so it ends up creating List<LinkedHashMap>

here is one solution that I know, works for class having a collection with a specific class type eg:

class D{
   private Map mapOfB // which should have been Map<String,B>
}

// this can be typed by using jackson's mixin 
abstract class DmixIn{
  @JsonDeserialize(contentAs = B.class)
  Map mapOfB
}

but how we can tell the type which is present in class A to Jackson as we can not pass ParameterizedType to contentAs, it just takes class instance.

I know we can write a custom deserializer to achieve the end result but I am looking for a more readable solution here, like any Jackson annotation or any simple config which we can be set on the property level.

and another issue(which can be because of my awareness) is I even need to maintain deserialization context while writing custom deserializers by using @JsonDeserialize(contentUsing = CustomDeserializer.class) because Class C references are reused and I may need to resolve IDs for this POJO while deserializing



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source