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中文網其他相關文章!