首頁 > Java > java教程 > 主體

在Java中,我們如何使用flexjson序列化物件清單?

WBOY
發布: 2023-09-05 23:09:06
轉載
687 人瀏覽過

在Java中,我們如何使用flexjson序列化物件清單?

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<strong>
</strong>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序列化物件清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板