Convert JSON to XML in Spring Boot

  • Last updated Apr 25, 2024

Follow these steps to convert JSON to XML in a Spring Boot application:

  1. Ensure that you have the necessary Jackson dependencies in your project. Add Jackson Dataformat XML library to your project. Jackson Dataformat XML helps to serialize POJOs to XML and deserialize XML to POJOs.
  2. For Maven:


    For Gradle:

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

  3. The code below demonstrates how to convert data from JSON to XML in Spring Boot:

  4. import;
    import com.fasterxml.jackson.core.exc.StreamWriteException;
    import com.fasterxml.jackson.databind.DatabindException;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.ObjectWriter;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.dataformat.xml.XmlMapper;
    import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
    public class JsonXMLExample {
      public static String convertJsonToXml(String json, String rootName) {
        ObjectMapper jsonMapper = new ObjectMapper();
        try {
          JsonNode jsonNode = jsonMapper.readValue(json, JsonNode.class);
          XmlMapper xmlMapper = new XmlMapper();
          xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
          xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
          xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
          ObjectWriter ow = xmlMapper.writer().withRootName(rootName);
          StringWriter sw = new StringWriter();
          ow.writeValue(sw, jsonNode);
          String xml = sw.toString();
          return xml;
        } catch (StreamWriteException e) {
        } catch (DatabindException e) {
        } catch (IOException e) {
        return null;
      public static void main(String[] args) throws IOException {
        String json = "{\"name\":\"Java Tutorials\",\"author\":\"Jake Parker\",\"language\":\"English\",\"price\":35.00}";
        String xml = convertJsonToXml(json, "Product");

    The output of the above code is as follows:

    <?xml version='1.1' encoding='UTF-8'?>
      <name>Java Tutorials</name>
      <author>Jake Parker</author>