Convert XML to JSON in Spring Boot

In this example tutorial, we will show you how to convert XML data to JSON in Spring Boot in two simple ways.

Required Dependencies

Add the following dependencies to your Spring Boot project:

  • Jackson Dataformat XML - This library helps to serialize POJOs to XML and deserialize XML to POJOs.
For Maven

Add to the pom.xml file:



For Gradle

Add to the build.gradle file:


implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.13.1'

You can find the other versions of Jackson Dataformat XML in the Jackson Dataformat XML Maven repository.

The following is a sample code with a method to convert XML data to JSON by binding XML data to a custom Java class object:


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToJsonExample {

	public String convertXmltoJson1(String xml) {
		XmlMapper xmlMapper = new XmlMapper();
		try {
			Book book = xmlMapper.readValue(xml, Book.class);
			ObjectMapper objMapper = new ObjectMapper();
			return objMapper.writeValueAsString(book);
		} catch (JsonMappingException ex) {
			ex.printStackTrace();
		} catch (JsonProcessingException ex) {
			ex.printStackTrace();
		}
		return null;
	}

}

Here is another example code to convert XML data to JSON by mapping xml to JsonNode object:


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

public class XmlToJsonExample {

	public String convertXmlToJson2(String xml) {
		XmlMapper xmlMapper = new XmlMapper();
		JsonNode jsonNode;
		try {
			jsonNode = xmlMapper.readTree(xml.getBytes());
			ObjectMapper objMapper = new ObjectMapper();
			return objMapper.writeValueAsString(jsonNode);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

}