2

I am using jackson as part of serializing and deserializing in my project (Spring Java). In normal scenarios where I have interface(contract) acting as field in POJO, then I use @JsonTypeInfo and @JsonSubTypes to achieve deserialization in polymorphic cases. But, right now, I have scenariio something like this:

public class classA {

    private contractA fieldA;
    
    //constructor and getter-setters.
}

then,

public interface contractA {
}

and finally,

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(/* concrete-class1 as name-value */),
        @JsonSubTypes.Type(/* concrete-class2 as name-value */),
})
public interface contractB extends contractA {
    //contract methods.
}

Now, when classA is passed as controller request body and I pass fieldA as concrete-class1 or concrete-class2, JsonSubTypes are not being used by jackson to deserialize into one of them. The reason why I did this and had two contracts is due to package dependencies. contractB is in different package as of contractA's. How can I configure on contractA using jackson that this class has its JsonSubTypeInfo specified in its subclasses.

Or, any other libraries or approaches are also welcomed.

Thank you !

Jeet Patel
  • 21
  • 4
  • Try to declare `@JsonTypeInfo` and `@JsonSubTypes` annotations over `ContractA` interface using [MixIn](https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations) feature. See [Jackson parse json with unwraping root, but without ability to set @JsonRootName](https://stackoverflow.com/questions/19568867/jackson-parse-json-with-unwraping-root-but-without-ability-to-set-jsonrootname) – Michał Ziober Aug 28 '20 at 20:38
  • Something similar answer I wrote here https://stackoverflow.com/a/63620373/3295987 – Hemant Patel Aug 30 '20 at 08:49
  • @PratapiHemantPatel I have `classA` and `contractA` in different package, say `package1`. And `contractB` in different package, say `package2`. And, `package2` has dependency of `package1`. So, I cannot refer `package2` classes in `package1`. And `concrete-class1`(and `concrete-class2`) are in `package2`. So, I cannot refer them as `@JsonSubTypes` on `contractA`, however I can refer them on `contractB`, that's why. – Jeet Patel Aug 30 '20 at 13:08

1 Answers1

0

This problem is later on solved by introducing our own custon JsonTypeInfo.

When the application is under deployment, we fetch all subclasses which is present in the JsonTypeInfo annotation (jackson like custom annotaion) and maintain a data-structure, that will be used while serializing and deserializing. This process is somewhat similar to the Jackson one (in addition to lookup for nested hierarches as well).

Jeet Patel
  • 21
  • 4