我们如何在Java中使用flexjson序列化对象列表?
该Flexjson 是一个轻量级的库序列化 和反序列化 Java对象到 和从 JSON 格式。我们可以使用JSONSerializer 类的serialize()方法来序列化 对象列表。此方法可以对目标实例执行浅 序列化。我们需要传递一个对象列表 的列表 类型作为参数传递给序列化()方法。
语法
public String serialize(Object target)
示例
import flexjson.JSONSerializer;
import java.util.*;
public class JsonSerializeListTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // pretty print JSON
Student s1 = new Student("Raja", "Ramesh", 28, "Hyderabad");
Student s2 = new Student("Suresh", "Kumar", 30, "Chennai");
Student s3 = new Student("Surya", "Krishna", 35, "Pune");
List<Student> students = Arrays.asList(s1, s2, s3);
String jsonStr = serializer.serialize(students);
System.out.println(jsonStr);
}
}
// Student classclass Student {
private String firstName;
private String lastName;
private int age;
private String address;
public Student() {}
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
public String toString() {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +
" ]";
}
}输出结果
[
{
"address": "Hyderabad",
"age": 28,
"class": "Student",
"firstName": "Raja",
"lastName": "Ramesh"
},
{
"address": "Chennai",
"age": 30,
"class": "Student",
"firstName": "Suresh",
"lastName": "Kumar"
},
{
"address": "Pune",
"age": 35,
"class": "Student",
"firstName": "Surya",
"lastName": "Krishna"
}
]