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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号