我正在尝试使用 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 回答
慕侠2389804
TA贡献1719条经验 获得超6个赞
我让它工作readValue在一个List
XmlMapper xmlMapper = new XmlMapper();
List list = xmlMapper.readValue(xml, List.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(list);
不知道为什么您的版本不起作用,似乎存在问题readTree和重复属性。看这篇文章,点5.1. Limitations
添加回答
举报
0/150
提交
取消