如何使用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)
Example
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?的详细内容,更多请关注其它相关文章!