如何为列表创建JSONArray

问题描述 投票:11回答:7

我有一个叫做的课

class Student {
   String name;
   String age;
}

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

public List<Student> getList(){

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

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

 return li;    
}

我需要将该列表转换为JSONArray

[{"name":"sam","age":"12"},{"name":"sri","age":"5"}]

任何人都可以帮助我这个吗?提前致谢..

java json list arraylist
7个回答
4
投票

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

使用JSONArrayJSONObject,您可以轻松地将该列表转换为JSON对象,如@Juniad answer


19
投票

使用Gson库将非常简单。

从JSON String到Object的ArrayList:

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

从对象的Array List到Json:

ArrayList<Student> sampleList = new ArrayList<Student>();
String json = new Gson().toJson(sampleList);

Gson库比JSONObjectJSONArray实现更简单。


17
投票

您必须在项目中包含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();
}


1
投票

json-lib可能是您正在寻找的库。你可以找到使用here的som例子。


1
投票

如果要将Object直接映射到json或者想将json转换为object,可以使用GSON库。这将为您提供更多的灵活性和控制力。

下载链接 - http://code.google.com/p/google-gson/

教程链接 - http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/


0
投票

像下面一样创建JSONArray。

JSONArray jsArray = new JSONArray(arrayList);

© www.soinside.com 2019 - 2024. All rights reserved.