List转JSON格式
将List的实例对象转为JSON格式:
- 导入fastjson包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
- 测试代码如下:
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> students = new ArrayList();
students.add(new Student("xx", 20));
students.add(new Student("xxx", 21));
String str = JSON.toJSONString(students); // List转json
System.out.println(str);
}
}
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = 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;
}
}