Flexjson库是一个轻量级的Java库,用于将Java beans、maps、arrays和collections序列化和反序列化为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 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; } }
{ "My_Employee": { "address": "Hyderabad", "age": 28, "class": "Employee", "firstName": "Adithya", "lastName": "Jai" } }
以上是如何使用Java中的flexjson来包装JSON?的详细内容。更多信息请关注PHP中文网其他相关文章!