Flexjson是一个轻量级库,用于序列化和反序列化Java对象 > 和来自JSON格式。我们可以使用 JSONSerializer 类的 serialize() 方法序列化对象列表。此方法可以对目标实例执行浅层序列化。我们需要将列表类型的对象列表作为参数传递给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 class
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) {
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"
}
]
以上就是在Java中,我们如何使用flexjson序列化对象列表?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。