Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 605
CL So Avatar asked Nov 19 '14 10:11

CL So


People also ask

What does Gson fromJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then, toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.

Is Gson multithreaded?

Gson instances are Thread-safe so you can reuse them freely across multiple threads. You can create a Gson instance by invoking new Gson() if the default configuration is all you need.


1 Answers

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());
like image 104
Prasad Khode Avatar answered Sep 29 '22 13:09

Prasad Khode