我使用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字符串。Answer to a similar question建议将xml string读入它的object类,而不是一般的list类。但是我尝试处理的XML文件是通用的,并且没有固定的POJO表示。我该如何处理这个问题?
谢谢!
发布于 2016-02-04 11:49:05
解决了问题。使用org.json.XML toJsonObject函数将XML转换为JSON。这个XML解析器能够解析复杂的XML文件,就像问题中提到的那样。
https://stackoverflow.com/questions/34872489
复制相似问题