Convert json to xml

There is various libraries that convert json to XML and in this example we will show how to convert json to XML using jackson's ObjectMapper and XmlMapper. In the set up, a browser class was created to hold browser information which we will map to below.

Setup

class Browser {
    private String name;

    public Browser(String name) {
        super();
        this.name = name;
    }
    
    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("name", name)
                .toString();
    }

    public String getName() {
        return name;
    }
}

Jackson

First we will create a string of json that represents a list of browsers. Next we will call ObjectMapper.readValue to transform the json into a list of browsers. Once converted we will then write the list of objects as xml.

@Test
public void convert_json_to_xml_jackson () throws IOException {
    
    String browsersAsJson ="[{\"name\":\"Chrome\"},{\"name\":\"FireFox\"},{\"name\":\"Internet Explorer\"}]\n";
    
    ObjectMapper jsonMapper = new ObjectMapper();
    
    @SuppressWarnings("unchecked")
    List<Browser> browsers = jsonMapper.readValue(browsersAsJson, List.class);

    XmlMapper xmlMapper = new XmlMapper();
    
    String browsersAsXml = xmlMapper.writeValueAsString(browsers);

    logger.info(browsersAsXml);

    assertTrue(browsersAsXml.length() > 0);
}

Output

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <element>
      <name>Chrome</name>
   </element>
   <element>
      <name>FireFox</name>
   </element>
   <element>
      <name>Internet Explorer</name>
   </element>
</root>