Java中如何将ArrayList转JSONArray呢?
下文笔者讲述将java代码中的Arraylist转换为JSONArray的方法分享,如下所示
ArrayList转JSONArray的实现思路
使用JSONArray.parseArray 方法 使用JSONObject.parseArray 方法 使用JSON.parseArray方法 即可将ArrayList转换为JSONArray例:ArrayList转JSONArray
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
public class ArrayListToJSONArray {
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
JSONArray studentJsonArray = new JSONArray();
Student a = new Student("猫猫", 19,"a");
Student b = new Student("狗狗", 18, "b");
Student c = new Student("maob", 21, "c");
studentList.add(a);
studentList.add(b);
studentList.add(c);
System.out.println("=============== studentList info ================");
System.out.println(studentList.toString());
// 方式 1
studentJsonArray = JSON.parseArray(JSONObject.toJSONString(studentList));
System.out.println("\n方式 1: " + studentJsonArray.toJSONString());
// 方式 2
studentJsonArray = JSON.parseArray(JSON.toJSONString(studentList));
System.out.println("\n方式 2: " + studentJsonArray.toJSONString());
// 方式 3
studentJsonArray = JSONObject.parseArray(JSONObject.toJSONString(studentList));
System.out.println("\n方式 3: " + studentJsonArray.toJSONString());
// 方式 4
studentJsonArray = JSONObject.parseArray(JSON.toJSONString(studentList));
System.out.println("\n方式 4: " + studentJsonArray.toJSONString());
// 方式 5
studentJsonArray = JSONArray.parseArray(JSONObject.toJSONString(studentList));
System.out.println("\n方式 5: " + studentJsonArray.toJSONString());
// 方式 6
studentJsonArray = JSONArray.parseArray(JSON.toJSONString(studentList));
System.out.println("\n方式 6: " + studentJsonArray.toJSONString());
System.out.println("\n============== Lambda 表达式 遍历 JSONArray ============");
studentJsonArray.forEach(student -> System.out.println("student info: " + student));
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


