使用 Jackson 库将 POJO 转换为 XML
Jackson是一个基于 Java 的库,可用于将 Java 对象转换为 JSON,并将 JSON 转换为 Java 对象。Jackson 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; } }
输出
<Person xmlns=""> <firstName>Raja</firstName> <lastName>Ramesh</lastName> <address>Hyderabad</address> </Person>
广告