我使用Jackson XmlMapper读取XML字符串并将其转换为JsonString。我的XML文件是:
<root>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk105">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk114">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
</root>
我为转换编写的代码是:
XmlMapper xmlMapper = new XmlMapper();
List entries = xmlMapper.readValue(file, List.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(entries);
我得到的Json字符串是:
{
"id": "569df9c1e4b0e505eb9fb913",
"json": [
{
"book": {
"id": "bk114",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
}
}
],
"fileType": "xml"
}
只有最后一本书被映射到Json String。 Answer to a similar question建议将xml字符串读入其对象类而不是通用列表类。但我尝试处理的XML文件是通用的,并没有固定的POJO表示。我该如何处理这个问题?
谢谢!
答案 0 :(得分:0)
解决了这个问题。使用org.json.XML toJsonObject函数将XML转换为JSON。此XML解析器能够解析复杂的XML文件,如问题中的那个。