Flexjson库是一个轻量级的Java库,用于将Java beans、maps、arrays和collections序列化和反序列化为JSON格式。JSONSerializer是执行Java对象到JSON的序列化的主要类,并且默认执行浅层序列化。我们可以使用JSONSerializer类的rootName()方法来包装一个JSON对象,该方法将结果JSON包装在一个包含一个名为rootName的字段的javascript对象中。
语法
public JSONSerializer rootName(String rootName)
登录后复制
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
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"
}
}
登录后复制
以上就是如何使用Java中的flexjson来包装JSON?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!