首頁  >  文章  >  Java  >  如何使用Java中的flexjson函式庫序列化一個map?

如何使用Java中的flexjson函式庫序列化一個map?

PHPz
PHPz轉載
2023-08-26 20:13:05876瀏覽

如何使用Java中的flexjson函式庫序列化一個map?

Flexjson是一個輕量級函式庫,用於將Java 物件序列化為JSON 格式以及反序列化為JSON 格式。我們也可以使用 JSONSerializer 類別的 serialize() 方法來序列化 Map,它對目標實例執行淺層序列化。

語法

public String serialize(Object target)

範例

import flexjson.JSONSerializer;
import java.util.*;
public class JsonSerializeMapTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
      Student student = new Student("Adithya", "Sai", 28, "Hyderabad");
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Student1", "Raja");
      map.put("Student2", "Ravi");
      map.put("my_student", student);
      String jsonStr = serializer.serialize(map);
      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 +" ]";
   }  
}

輸出

{
   "my_student": {
      "address": "Hyderabad",
      "age": 28,
      "class": "Student",
      "firstName": "Adithya",
      "lastName": "Sai"
 },
 "Student1": "Raja",
 "Student2": "Ravi"
}

以上是如何使用Java中的flexjson函式庫序列化一個map?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除