my question is not same is this question. if i want to explain lets assume we have these classes (A, B, C).
@Data
@NoArgsConstructor
class A {
private Integer x;
private String type;
public A(String type, Integer x) {
this.type = type;
this.x = x;
}
}
@Data
class B extends A {
private Integer y;
public B(Integer x, Integer y) {
super("B", x);
this.y = y;
}
}
@Data
class C extends A {
private Integer z;
public C(Integer x, Integer z) {
super("C", x);
this.z = z;
}
}
know i want to parse an array which their base classes is A. and with property named type i want to convert each item to its specific class. something like this code.
public static void main(String[] args) {
Gson gson = new Gson();
List<A> list = new ArrayList<>();
A a = new A("A", 0);
list.add(a);
B b = new B(1, 2);
list.add(b);
C c = new C(3, 4);
list.add(c);
String serializedJson = gson.toJson(list);
List<? extends A> deserializedList = gson.fromJson(serializedJson, new TypeToken<List<? extends A>>() {
}.getType());
for (A item : deserializedList) {
System.out.println(item.getType());
if (item instanceof B) {
System.out.println(((B) item).getY());
} else if (item instanceof C) {
System.out.println(((C) item).getZ());
}
}
}
serialized json is something like this
[{"x":0,"type":"A"},{"y":2,"x":1,"type":"B"},{"z":4,"x":3,"type":"C"}]
in real world, i have something like this json and want to parse it. but when i run the code y and z properties not printed and objects are not instance of B or C. how to achieve to this goal to parse and create each item with type property.
listasList<A>- instead of something likeList<? extends A>?