如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist?

编程入门 行业动态 更新时间:2024-10-25 04:20:20
本文介绍了如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想将一个数组列表存储到磁盘,所以我使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:43:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884925.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何使用   列表   gson   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!