如何在Java中使用flexjson包装JSON?
该Flexjson库 是一个轻量级的 Java库,用于序列化和反序列化的Javabean,映射,数组,并集合 在一个JSON格式。一个JSONSerializer 是执行的Java序列化对象到JSON,默认情况下执行一个主类浅 序列化。我们可以使用JSONSerializer 类的rootName()方法包装JSON对象,此方法将所得的JSON包装在包含单个名为rootName的字段的javascript对象中。
语法
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 classclass 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" } }