如何使用 Java 中的 JSON-lib API 将 bean 转换为 XML?
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>
广告