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>
以上是在Java中使用Jackson库将POJO转换为XML?的详细内容。更多信息请关注PHP中文网其他相关文章!