在Java編程中,常常需要將List轉換成JSON格式字符串進行數據傳輸和存儲。下面介紹一種常用的方法:
//導入相關包 import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSON; import java.util.List; import java.util.ArrayList; //定義一個Person實體類 public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } //創建一個Person List ListpersonList = new ArrayList (); Person person1 = new Person(); person1.setName("張三"); person1.setAge(18); personList.add(person1); Person person2 = new Person(); person2.setName("李四"); person2.setAge(20); personList.add(person2); //將Person List轉換成JSON格式字符串 String jsonString = JSON.toJSONString(personList); System.out.println(jsonString); //輸出:[{"age":18,"name":"張三"},{"age":20,"name":"李四"}] //將JSON格式字符串轉換成Person List List resultList = JSONObject.parseArray(jsonString, Person.class); System.out.println(resultList.get(0).getName()); //輸出:張三