Flexjson là thư viện nhẹ hỗ trợ serialize và deserialize đối tượng Java sang/định dạng JSON. Để serialize một danh sách đối tượng, ta dùng phương thức serialize() của lớp JSONSerializer. Phương thức này thực hiện serialization nông (shallow serialization) trên đối tượng mục tiêu.
Cú pháp
public String serialize(Object target)
Ví dụ hoàn chỉnh
import flexjson.JSONSerializer;
import java.util.*;
public class JsonSerializeListDemo {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // format đẹp
Student s1 = new Student("An", "Nguyễn", 22, "Hà Nội");
Student s2 = new Student("Bình", "Trần", 25, "Hồ Chí Minh");
Student s3 = new Student("Cường", "Lê", 28, "Đà Nẵng");
List<Student> students = Arrays.asList(s1, s2, s3);
String jsonStr = serializer.serialize(students);
System.out.println(jsonStr);
}
}
// Lớp Student
class 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) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
// Getters
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public int getAge() { return age; }
public String getAddress() { return address; }
@Override
public String toString() {
return "Student[firstName=" + firstName + ", lastName=" + lastName +
", age=" + age + ", address=" + address + "]";
}
}
Kết quả
[
{
"address": "Hà Nội",
"age": 22,
"class": "Student",
"firstName": "An",
"lastName": "Nguyễn"
},
{
"address": "Hồ Chí Minh",
"age": 25,
"class": "Student",
"firstName": "Bình",
"lastName": "Trần"
},
{
"address": "Đà Nẵng",
"age": 28,
"class": "Student",
"firstName": "Cường",
"lastName": "Lê"
}
]
Mẹo: Flexjson tự động thêm trường class để hỗ trợ deserialization. Có thể tùy chỉnh bằng annotation @JSON.