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库比使用JSONObject和JSONArray实现更简单.
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)
像下面这样创建 JSONArray。
JSONArray jsArray = new JSONArray(arrayList);
我认为你不需要下载 jettison jar 文件。
使用JSONArray并且JSONObject您可以轻松将该列表转换为 JSON 对象,如 @Juniad 答案
| 归档时间: |
|
| 查看次数: |
65367 次 |
| 最近记录: |