Maison  >  Article  >  Java  >  Comment sérialiser une carte à l'aide de la bibliothèque flexjson en Java ?

Comment sérialiser une carte à l'aide de la bibliothèque flexjson en Java ?

PHPz
PHPzavant
2023-08-26 20:13:05829parcourir

Comment sérialiser une carte à laide de la bibliothèque flexjson en Java ?

Flexjson est une bibliothèque légère permettant de sérialiser et de désérialiser des objets Java vers et depuis le format JSON. Nous pouvons également sérialiser une Map en utilisant la méthode serialize() de la classe JSONSerializer, qui effectue une sérialisation superficielle sur l'instance cible.

Syntaxe

public String serialize(Object target)

Exemple

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 +" ]";
   }  
}

Sortie

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer