如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist? [英] How to use gson to convert json to arraylist if the list contain different class?

查看:24
本文介绍了如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数组列表存储到磁盘,所以我使用 gson 将其转换为字符串

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;
}

输出字符串:

[{"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?

推荐答案

你可以使用下面的代码将json转换为对应的对象列表

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());

这篇关于如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆