Home  >  Article  >  Java  >  How to wrap JSON using flexjson in Java?

How to wrap JSON using flexjson in Java?

PHPz
PHPzforward
2023-09-16 19:01:021079browse

How to wrap JSON using flexjson in Java?

Flexjson library is a lightweight Java library for serializing and deserializing Java beans, maps, arrays and collections into JSON format. JSONSerializer is the main class that performs serialization of Java objects to JSON, and performs shallow serialization by default. We can wrap a JSON object using the rootName() method of the JSONSerializer class, which wraps the resulting JSON in a javascript object containing a field named rootName. The Chinese translation of

Grammar

public JSONSerializer rootName(String rootName)

Example

is:

Example

import flexjson.JSONSerializer;
public class JSONRootNameTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().rootName("My_Employee").prettyPrint(true);
      Employee emp = new Employee("Adithya", "Jai", 28, "Hyderabad");
      String jsonStr = serializer.serialize(emp);
      System.out.println(jsonStr);
   }
}
// Employee class<strong>
</strong>class Employee {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Employee() {}
   public Employee(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;
   }
}

Output

{
 "My_Employee": {
 "address": "Hyderabad",
 "age": 28,
 "class": "Employee",
 "firstName": "Adithya",
 "lastName": "Jai"
 }
}

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

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete