How to use gson to convert json to arraylist if the list contain different class?

27,824

Solution 1

you can use the below code to convert json to corresponding list of objects

TypeToken<List<Animal>> token = new TypeToken<List<Animal>>() {};
List<Animal> animals = gson.fromJson(data, token.getType());

Solution 2

Kotlin example:

val gson = Gson()
val typeToken = object : TypeToken<ArrayList<Animal>>() {}
val list = gson.fromJson<ArrayList<Animal>>(value, typeToken.type)

Faster way:

val gson = Gson()
val array = gson.fromJson<Array<Animal>>(value, Array<Animal>::class.java)
val arrayList = ArrayList(array.toMutableList())
Share:
27,824
CL So
Author by

CL So

Updated on September 06, 2020

Comments

  • CL So
    CL So over 3 years

    I want to store an arraylist to disk, so I use gson to convert it to string

        ArrayList<Animal> anim=new ArrayList<Animal>();
        Cat c=new Cat();
        Dog d=new Dog();
        c.parentName="I am animal C";
        c.subNameC="I am cat";
        d.parentName="I am animal D";
        d.subNameD="I am dog";
        anim.add(c);
        anim.add(d);
        Gson gson=new Gson();
        String json=gson.toJson(anim);
    
    
    
    public class Animal {
    
        public String parentName;
    }
    
    public class Cat extends Animal{
        public String subNameC;
    }
    
    public class Dog  extends Animal{
        public String subNameD;
    }
    

    output string:

    [{"subNameC":"I am cat","parentName":"I am animal C"},{"subNameD":"I am dog","parentName":"I am animal D"}]
    

    Now I want use this string to convert back to arraylist

    I know I should use something like:

        ArrayList<Animal> anim = gson.fromJson(json, ArrayList<Animal>.class);
    

    But this is not correct, what is the correct syntax?

  • CL So
    CL So over 9 years
    This works, but I can cast list item to subclass (Cat)anim.get(0) in original list while the new list cannot (Cat)animals.get(0), can I save the type for each item to json and restore them to java object?
  • CL So
    CL So over 9 years
    I found another problem, now the list is <ArrayList<ArrayList<Animal>>>, I tried TypeToken<List<List<Animal>>> token = new TypeToken<List<List<Animal>>>() {}; and TypeToken<ArrayList<ArrayList<Animal>>> token = new TypeToken<ArrayList<ArrayList<Animal>>>() {};, both throw exception class android.widget.Editor$InsertionHandleView declares multiple JSON fields named mDownPositionY, how to get object from 2D json?
  • Prasad Khode
    Prasad Khode over 9 years
    for the first problem this may help you
  • gschambial
    gschambial over 6 years
    Helped me. Thanks.
  • Prasad Khode
    Prasad Khode over 6 years
    @gschambial I'm glad it helped you... :)