Posted In: Jackson 2X, JSON, XML

How to convert XML to POJO 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 XmlToPojo {

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

		try {
			XmlMapper xmlMapper = new XmlMapper();
			Dependency pojo = xmlMapper.readValue(getXmlString(),
			        Dependency.class);
			System.out.println(pojo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getXmlString() {
		return "<dependency> <groupId>org.json</groupId>"
		        + "<artifactId>json</artifactId>"
		        + "<version>20160807</version>" + "</dependency>";
	}
}

Result

Dependency [groupId=org.json, artifactId=json, version=20160807]

Tags:

by , on September 1st, 2017