How to use gson to convert json to arraylist if the list contains another class?

I want to save 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 line:

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

Now I want to use this line to convert back to arraylist

I know that I should use something like:

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

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

+6
source share
1 answer

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

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

Source: https://habr.com/ru/post/978386/


All Articles