Posted In: Jackson 2X, JSON, XML

How to convert POJO to XML using Jackson library

Maven

<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.0</version>
</dependency>

Dependency POJO

public class Dependency implements Serializable {
	private String groupId;
	private String artifactId;
	private String version;
................
//getter setter
}

Jackson 2X XmlMapper

package com.example.csv;

import org.junit.Test;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class PojoToXml {

	@Test
	public void xmltojson() throws Exception {
		System.out.println("xmltojson started");

		try {
			XmlMapper xmlMapper = new XmlMapper();
			Dependency pojo = new Dependency();
			pojo.setGroupId("org.json");
			pojo.setArtifactId("json");
			pojo.setVersion("20160807");
			String xml = xmlMapper.writeValueAsString(pojo);
			System.out.println(xml);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Result

<Dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160807</version>
</Dependency>

Tags:

by , on September 1st, 2017