欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java list轉(zhuǎn)json格式

洪振霞1年前8瀏覽0評論

在Java編程中,常常需要將List轉(zhuǎn)換成JSON格式字符串進(jìn)行數(shù)據(jù)傳輸和存儲。下面介紹一種常用的方法:

//導(dǎo)入相關(guān)包
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import java.util.List;
import java.util.ArrayList;
//定義一個(gè)Person實(shí)體類
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;
}
}
//創(chuàng)建一個(gè)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轉(zhuǎn)換成JSON格式字符串
String jsonString = JSON.toJSONString(personList);
System.out.println(jsonString); //輸出:[{"age":18,"name":"張三"},{"age":20,"name":"李四"}]
//將JSON格式字符串轉(zhuǎn)換成Person List
ListresultList = JSONObject.parseArray(jsonString, Person.class);
System.out.println(resultList.get(0).getName()); //輸出:張三