如何使用 Java 中的 flexjson 序列化对象数组?

javajsonobject oriented programmingprogramming

Flexjson  是一个 轻量级  库,用于将 Java 对象序列化 反序列化 为 JSON 格式。我们还可以使用 JSONSerializer  类的  ser​​ialize()  方法序列化对象数组,这将对目标实例执行浅层序列化。

语法

public String serialize(Object target)

在下面的程序中,我们需要序列化对象数组。

示例

import flexjson.JSONSerializer;
public class JsonSerializeArrayTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
      Student stud1 = new Student("Adithya", "Sai", 28, "Hyderabad");
      Student stud2 = new Student("Jai", "Dev", 30, "Chennai");
      Student stud3 = new Student("Ravi", "Chandra", 35, "Pune");
      Student[] students = {stud1, stud2, stud3};
      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": "Adithya",
 "lastName": "Sai"
 },
 {
 "address": "Chennai",
 "age": 30,
 "class": "Student",
 "firstName": "Jai",
 "lastName": "Dev"
 },
 {
 "address": "Pune",
 "age": 35,
 "class": "Student",
 "firstName": "Ravi",
 "lastName": "Chandra"
 }
]

相关文章