我正在使用 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 字符串。 回答一个类似的问题,建议将 xml 字符串读入它的对象类而不是通用列表类。但是我试图处理的 XML 文件是通用的,没有固定的 POJO 表示。我该如何处理这个问题?
谢谢!