如何在不使用 Java 中的 JSON-lib API 的型別提示的情況下將 bean 轉換為 XML?
JSON-lib 是一個 Java 庫,用來以 JSON 格式序列化和反序列化 java bean、對映、陣列和集合。使用 XMLSerializer 類的 setTypeHintsEnabled() 方法,可以將 bean 轉換為 XML,且無需型別提示,此方法設定了 JSON 型別是否可以作為屬性包含。可以向此方法傳遞 false 作為引數來停用 XML 中的型別提示。
語法
public void setTypeHintsEnabled(boolean typeHintsEnabled)
示例
import net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; public class ConvertBeanToXMLNoHintsTest { public static void main(String[] args) { Employee emp = new Employee("Krishna Vamsi", 115, 30, "Java"); JSONObject jsonObj = JSONObject.fromObject(emp); System.out.println(jsonObj.toString(3)); //pretty print JSON XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled(false); // this method disable type hints String xml = xmlSerializer.write(jsonObj); System.out.println(xml); } public static class Employee { private String empName, empSkill; private int empId, age; public Employee(String empName, int empId, int age, String empSkill) { super(); this.empName = empName; this.empId = empId; this.age = age; this.empSkill = empSkill; } public String getEmployeeName() { return empName; } public int getEmployeeId() { return empId; } public String getEmployeeSkill() { return empSkill; } public int getAge() { return age; } } }
輸出
{ "employeeName": "Krishna Vamsi", "employeeSkill": "Java", "employeeId": 115, "age": 30 } <?xml version="1.0" encoding="UTF-8"?> <o> <age>30</age> <employeeId>115</employeeId> <employeeName>Krishna Vamsi</employeeName> <employeeSkill>Java</employeeSkill> </o>
廣告