一个杰克逊是一个基于Java的库,它可以为Java对象到JSON和JSON转换为Java对象很有用。一个杰克逊API是快于其他的API,需要更少的内存区域,对于大型物体良好。我们使用XmlMapper类的writeValueAsString()方法将POJO转换为XML格式,并且需要将相应的POJO实例作为参数传递给此方法。
语法public String writeValueAsString(Object value) throws JsonProcessingException
示例import com.fasterxml.jackson.dataformat.xml.*;
public class POJOToXmlTest {
public static void main(String args[]) throws Exception {
try {
XmlMapper xmlMapper = new XmlMapper();
Person pojo = new Person();
pojo.setFirstName("Raja");
pojo.setLastName("Ramesh");
pojo.setAddress("Hyderabad");
String xml = xmlMapper.writeValueAsString(pojo);
System.out.println(xml);
} catch(Exception e) {
e.printStackTrace();
}
}
}
// Person class
class Person {
private String firstName;
private String lastName;
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
输出结果
Raja
Ramesh
Hyderabad