net.sf.json.xml.XMLSerializer類別是一個用於將JSON轉換為XML的實用工具類別。在將JSONObject實例轉換為XML時,該類別可以新增提示以便轉換回JSON。我們可以使用XMLSerializer類別的write()方法將JSON值寫入一個帶有UTF-8編碼的XML字串中,並且它可以傳回一個格式良好的XML文檔的字串表示。
public String write(JSON json)
import net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; public class ConvertBeanToXMLTest { public static void main(String[] args) { Student student = new Student("Sai", "Adithya", 25, "Pune"); JSONObject jsonObj = JSONObject.fromObject(student); System.out.println(jsonObj.toString(3)); //pretty print JSON XMLSerializer xmlSerializer = new XMLSerializer(); String xml = xmlSerializer.write(jsonObj); System.out.println(xml); } public static class Student { private String firstName, lastName, address; public int age; public Student(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; } } }
{ "firstName": "Sai", "lastName": "Adithya", "address": "Pune", "age": 25 } <?xml version="1.0" encoding="UTF-8"?> <o> <address type="string">Pune</address> <age type="number">25</age> <firstName type="string">Sai</firstName> <lastName type="string">Adithya</lastName> </o> <!--?xml version="1.0" encoding="UTF-8"?-->
以上是如何使用Java中的JSON-lib API將一個bean轉換為XML?的詳細內容。更多資訊請關注PHP中文網其他相關文章!