Home > Java > javaTutorial > body text

How to serialize a map using the flexjson library in Java?

PHPz
Release: 2023-08-26 20:13:05
forward
883 people have browsed it

How to serialize a map using the flexjson library in Java?

Flexjson is a lightweight library for serializing and deserializing Java objects into JSON format. JSON format. We can also serialize a Map using the serialize() method of the JSONSerializer class, which performs shallow serialization on the target instance.

Syntax

public String serialize(Object target)
Copy after login

Example

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

Output

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

The above is the detailed content of How to serialize a map using the flexjson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template