Jackson不会将XML文件完全解析为JSON

时间:2019-04-18 07:58:50

标签: java json jackson modelmapper

我正在尝试使用Jackson将xml字符串解析为JSON。

此刻我正在使用以下字符串:

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>";

这是我正在使用的代码:

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

但是解析器似乎只能得到一个节点:

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

如何将所有节点转换为JSON?

谢谢

1 个答案:

答案 0 :(得分:1)

我使用readValueList

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

不确定您的版本为什么不起作用,readTree和重复的属性似乎存在问题。参见this article,指向5.1. Limitations