Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moshi : converting JSON to Java object when the class has a List<Object> field

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.

like image 276
Stéphane Avatar asked Aug 13 '26 07:08

Stéphane


1 Answers

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);
like image 138
Stéphane Avatar answered Aug 14 '26 21:08

Stéphane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!