该Flexjson库是一个轻量级的Java库,用于序列化和反序列化的Java bean,映射,数组,并集合在一个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"
}
}