如何为List <Class name>创建JSONArray

Nav*_*uel 13 java json list arraylist

我有一个叫做的课

class Student {
   String name;
   String age;
}
Run Code Online (Sandbox Code Playgroud)

我有一个返回List对象的方法

public List<Student> getList(){

 List<Student> li =new ArrayList();
 ....

 li.add(new Student('aaa','12'));
 ... 

 return li;    
}
Run Code Online (Sandbox Code Playgroud)

我需要将该列表转换为JSONArray

[{"name":"sam","age":"12"},{"name":"sri","age":"5"}]
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我这个吗?先谢谢你...

Man*_*dit 19

使用Gson库将非常简单.

从JSON String到Object的ArrayList:

Type listType = 
     new TypeToken<ArrayList<Student>>(){}.getType();
ArrayList<Student> yourClassList = new Gson().fromJson(jsonArray, listType);
Run Code Online (Sandbox Code Playgroud)

从对象的Array List到Json:

ArrayList<Student> sampleList = new ArrayList<Student>();
String json = new Gson().toJson(sampleList);
Run Code Online (Sandbox Code Playgroud)

Gson库比使用JSONObjectJSONArray实现更简单.

  • 你救了我的晚上..!谢谢, (2认同)

JHS*_*JHS 18

您必须jettison在项目中包含jar并导入所需的类.

JSONObject jObject = new JSONObject();
try
{
    JSONArray jArray = new JSONArray();
    for (Student student : sudentList)
    {
         JSONObject studentJSON = new JSONObject();
         studentJSON.put("name", student.getName());
         studentJSON.put("age", student.getAge());
         jArray.put(studentJSON);
    }
    jObject.put("StudentList", jArray);
} catch (JSONException jse) {
    jse.printStacktrace();
}
Run Code Online (Sandbox Code Playgroud)


vit*_*yoz 5

像下面这样创建 JSONArray。

JSONArray jsArray = new JSONArray(arrayList);

  • 如果这样有效就好了。我得到了一个充满空值的 JSONArray。 (3认同)

Moh*_*mar 4

我认为你不需要下载 jettison jar 文件。

使用JSONArray并且JSONObject您可以轻松将该列表转换为 JSON 对象,如 @Juniad 答案

  • 你愿意详细说明@Juniad 的答案是什么吗?目前它还不存在。 (5认同)