添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
腹黑的板凳  ·  DateUtil (hutool ...·  8 小时前    · 
淡定的茶壶  ·  anti-emulator/AntiEmul ...·  9 小时前    · 
豪气的苹果  ·  Android social ...·  10 小时前    · 
风流倜傥的爆米花  ·  TDengine Go Connector ...·  11 小时前    · 
很酷的钢笔  ·  C++ STL IO流 与 Unicode ...·  14 小时前    · 
失望的针织衫  ·  Amazon.com·  1 月前    · 
发怒的洋葱  ·  录象带教学片-中文学院·  2 月前    · 
不拘小节的黄花菜  ·  Using Babel Plugin ...·  2 月前    · 
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.13.0</version>
</dependency>

After importing Jackson, we can start using its XmlMapper class for reading and writing XML.

XmlMapper xmlMapper = new XmlMapper();
//POJO -> XML
String xml = xmlMapper.writeValueAsString(pojo);
//XML -> POJO
Class pojo = xmlMapper.readValue(xml);

See Also: Jackson – Marshal and Unmarshal Java Objects to JSON

2. XMLMapper class

XMLMapper is the most important class for handling XML documents with Jackson. It provides methods to read and write XML to the following sources and targets.

  • String
  • Byte[]
  • java.io.File
  • java.io.InputStream and java.io.OutputStream
  • java.io.Reader and java.io.Writer
//Write to String
String xml = xmlMapper.writeValueAsString(pojo);
//Write to file
xmlMapper.writeValue(new File("data.xml"), pojo);
//Read from String
Pojo pojo = xmlMapper.readValue(xmlString, Pojo.class);
//Read from File
Pojo pojo = xmlMapper.readValue(new File("data.xml"), Pojo.class);

Using its enable() and disable() methods, we can trun on and off various behaviors specific to XML marshalling and unmarshalling such as:

  • Handling null and empty values.
  • Handling date and time values
  • Handling enum values
  • Handling elements ordering
  • Pretty printing, etc.
xmlMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
xmlMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

3. Customing Conversion with Jackson Annotations

Let us take an example of Article class. We will first check the default XML generated for its instance, and then we will customize the XML by applying annotations to the Article class.

class Article {
	private Long id;
	private String title;
	private List<String> tags;
	//Constructors, getters, setters and toString method

In the following examples, we use the same code for marshalling.

XmlMapper xmlMapper = new XmlMapper();
Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2"));
String articleXml = xmlMapper.writeValueAsString(article);
System.out.println(articleXml);

3.1. Default XML without Annotations

The default XML takes the XML tag names from class and member field names, including capitalization.

<Article><id>1</id><title>Test Title</title><tags><tags>Tag1</tags><tags>Tag2</tags></tags></Article>

3.2. Root Element’s Name

Use @JacksonXmlRootElement to customize the name of the root element.

@JacksonXmlRootElement(localName = "article")
class Article { ... }

Check out the generated XML putout.

<article>....</article>

3.3. Making XML Attribute

Use @JacksonXmlProperty(isAttribute = true) to mark a field as an XML attribute rather than an XML element.

@JacksonXmlRootElement(localName = "article")
class Article {
	@JacksonXmlProperty(isAttribute = true)
	private Long id;

Check out the generated XML putout.

<article id="1">...</article>

3.4. Customizing Lists

Use @JacksonXmlElementWrapper to on a List type to create the list wrapper element. The individual elements can be customized using the @JacksonXmlProperty.

@JacksonXmlRootElement(localName = "article")
class Article {
	@JacksonXmlProperty(isAttribute = true)
	private Long id;
	private String title;
	@JacksonXmlElementWrapper(localName = "tags")
	@JacksonXmlProperty(localName = "tag")
	private List<String> tags;

Check out the generated XML putout.

<article id="1"><title>Test Title</title><tags><tag>Tag1</tag><tag>Tag2</tag></tags></article>

4. Pretty Printing the XML Output

If we want to pretty print the XML output then we can turn on the SerializationFeature.INDENT_OUTPUT on XMLMapper.

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2"));
String articleXml = xmlMapper.writeValueAsString(article);
System.out.println(articleXml);

It will print the following XML.

<article id="1">
  <title>Test Title</title>
    <tag>Tag1</tag>
    <tag>Tag2</tag>
  </tags>
</article>

5. Conclusion

This Jackson tutorial taught us to serialize and deserialize the Java Object to XML document with simple and easy examples. We learned to customize and use the XmlMapper class for controlling the specific behavior during the conversion processes.

Happy Learning !!

Sourcecode on Github

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter