Search code examples
javajsonjacksonmodelmapper

Jackson won't parse XML file to JSON entirely


I'm trying to parse an xml string into JSON using Jackson.

At the moment I'm using this string:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                " <rootNode>\n" +
                "    <data>\n" +
                "        <cityCode>R8</cityCode>\n" +
                "        <place>\n" +
                "            <code>01</code>\n" +
                "        </place>\n" +
                "    </data>\n" +
                "    <data>\n" +
                "        <cityCode>R9</cityCode>\n" +
                "        <place>\n" +
                "            <code>02</code>\n" +
                "        </place>\n" +
                "    </data>\n" +
                "</rootNode>";

Here is the code I'm using:

XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(xml);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node)

But the parser only seems to get one node:

{"data":{"cityCode":"R9","place":{"code":"02"}}}

How can I get all the nodes converted into JSON?

Thank you


Solution

  • I get it working using readValue into a List

    XmlMapper xmlMapper = new XmlMapper();
    List list = xmlMapper.readValue(xml, List.class);
    ObjectMapper jsonMapper = new ObjectMapper();
    String json = jsonMapper.writeValueAsString(list);
    

    Not sure why your version does not work, there seem to be issues with readTree and repeated attributes. See this article, point 5.1. Limitations