如何使用Java中的JSON-lib API将bean转换为没有类型提示的XML?
该JSON-lib的是一个Java库,用于序列化和反序列化的Javabean,映射,数组和JSON格式的集合。我们可以 使用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>热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短