gpt4 book ai didi

android - 在 Android 上从任何容器(如 List)创建 GSON

转载 作者:行者123 更新时间:2023-11-29 20:15:57 24 4
gpt4 key购买 nike

我有一个 java.util.List<Student>;而 Student 是一个简单的类,只有很少的属性,例如 String name , String forName , int id , double averageCredtis ;

在这段代码中:

class Student {
private String foreName;
private String surName;
private int id;
private double averageCredits;

public Student(String f, String n, int id, double aCred)
{
this.foreName = f;
this.surName = n;
this.id = id;
this. averageCredits = aCred;
}
}

然后我在运行时创建多个对象:

Student a = new Student("Alice", "Aaa", 123, 1.6);
Student b = new Student("Bob", "Bbb", 223, 1.0);
Student c = new Student("Chris", "Ccc", 457, 3.6);

我曾经通过 myList.add(a); 将它们存储在一个 Listdt 中.

我想生成一个像这样的 GSON 字符串:

{ "GlobalVal": "Value", "GlobalNumber": "234", "Student": {"Surname": "Aaa","Forename": "Alice", "id": 123, >"averageCredit": 1.7 } "Student": {"Surname": "Bbb","Forename": "Bob", "id": >223,"averageCredit": 1.0 } }

最佳答案

创建一个名为Container的类

class Container{
String globalVal;
int globalInt;
List<Student> students;
}

使用GSON将其转换为 JSON 的库。创建上述类的实例并存储值。

Container obj = new Container();
Gson gson = new Gson();

// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

关于android - 在 Android 上从任何容器(如 List)创建 GSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33892985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com