Posted In: Jackson 2X, JSON, XML

How to convert XML to JSON using Jackson library

<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>
package com.example.csv;

import org.junit.Test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToJson2 {

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

		try {
			XmlMapper xmlMapper = new XmlMapper();
			JsonNode node = xmlMapper.readTree(getXmlString().getBytes());

			ObjectMapper jsonMapper = new ObjectMapper();
			String json = jsonMapper.writeValueAsString(node);
			System.out.println(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

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

Result

{“groupId”:”org.json”,”artifactId”:”json”,”version”:”20160807″}

Tags:

by , on September 1st, 2017