Convert JSON to XML in Spring Boot

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:

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.15.2</version>
    </dependency>

    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 java.io.IOException;
    import java.io.StringWriter;
    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) {
          e.printStackTrace();
        } catch (DatabindException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        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");
    
        System.out.println(xml);
      }
    
    }

    The output of the above code is as follows:

    <?xml version='1.1' encoding='UTF-8'?>
    <Product>
      <name>Java Tutorials</name>
      <author>Jake Parker</author>
      <language>English</language>
      <price>35.0</price>
    </Product>