Let's say I have something like this:
public class Container implements Serializable {
private List<Object> elements;
[... some other fields ...]
}
public class A implements Serializable {
...
}
public class B implements Serializable {
...
}
public class C implements Serializable {
...
}
Where the List<Object> elements contains objects of type A, B or C
I use Moshi to convert it to JSON (and it works perfectly) and convert it back to Java. The conversion back to Java doesn't work.
It seems the List<Object> elements cannot be converted back, and all elements of the list are converted to LinkedHashTreeMap objects.
What would be the best way to solve this? (if there is a way!)
Thank you.
The answer from Jesse Wilson works perfectly:
public class Container implements Serializable {
private List<Item> elements;
[... some other fields ...]
}
public abstract class Item implements Serializable {}
public class A extends Item {
...
}
public class B extends Item {
...
}
public class C extends Item {
...
}
...
Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(Item.class, "item_type")
.withSubtype(A.class, "a")
.withSubtype(B.class, "b")
.withSubtype(C.class, "c"))
.build();
containerAdapter = moshi.adapter(Container.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With