I have some class structure like this
class A {
private List<B> b;
public List<B> getB() {
return b;
}
public void setB(List<B> b) {
this.b = b;
}
}
@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="@class")
abstract class B {
}
@JsonTypeInfo(use=Id.NONE)
class C extends B {
}
@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="@class")
class D extends B {
}
When I use ObjectMapper (fasterxml) to write it in JSON format for instance of C and D, D has "@class" while C does not. It meets my expectation.
However, when I apply it on instance of class A, "@class" shows on all values, even if it's instance of C. In the other hand, I remove @JsonTypeInfo on class B, the "@class" does not exist even if it's instance of D.
This is my testing code
List<B> list = new ArrayList<B>();
list.add(new D());
list.add(new C());
list.forEach(p->{try {
System.out.println(mapper.writeValueAsString(p));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}});
A a = new A();
a.setB(list);
System.out.println(mapper.writeValueAsString(a));
How can I make "@class" shown when it needed?
At this time, I need to refactor the structure of my model by using two separate the class, a class contains the Id=CLASS, the other is NONE.
I hope there are some better solution on this.