如何使用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>
以上是 如何使用Java中的JSON-lib API将bean转换为XML? 的全部内容, 来源链接: utcz.com/z/326880.html