Flexjson 在 Java 中如何包装 JSON?
Flexjson 库 是一个轻量级Java 库,用于以 JSON 格式序列化和反序列化Java Bean、映射、数组和集合。JSONSerializer 是用于将 Java 对象序列化为 JSON 的主类,并且默认情况下执行浅层序列化。我们可以使用JSONSerializer 类的 rootName() 方法包装 JSON 对象,此方法将结果 JSON 作为 JavaScript 对象,其中包含一个名为 rootName 的字段。
语法
public JSONSerializer rootName(String rootName)
示例
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 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; } }
输出
{ "My_Employee": { "address": "Hyderabad", "age": 28, "class": "Employee", "firstName": "Adithya", "lastName": "Jai" } }
广告