Home > Java > javaTutorial > body text

How to wrap JSON using flexjson in Java?

PHPz
Release: 2023-09-16 19:01:02
forward
1136 people have browsed it

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)
Copy after login

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

Output

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

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!

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