Jackson XmlMapper XML到Json的转换问题 [英] Jackson XmlMapper XML to Json conversion issue
问题描述
我正在使用Jackson XmlMapper读取XML字符串并将其转换为JsonString。我的XML文件是:
I'm using the Jackson XmlMapper to read an XML string and convert it to a JsonString. My XML file is:
<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>
我为转换编写的代码是:
The code I've written for the conversion is :
XmlMapper xmlMapper = new XmlMapper();
List entries = xmlMapper.readValue(file, List.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(entries);
我得到的Json字符串是:
The Json String I'm getting as output is:
{
"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。
回答类似问题问题建议将xml字符串读入其对象类而不是通用列表类。但我正在尝试处理的XML文件是通用的,没有固定的POJO表示。我该如何处理这个问题?
Only the last book is being mapped to the Json String. Answer to a similar question suggested to read the xml string into it's object class rather than a generic list class. But the XML file I'm trying to process is generic and doesn't have a fixed POJO representation. How do I handle this issue?
谢谢!
推荐答案
解决问题。使用org.json.XML toJsonObject函数将XML转换为JSON。此XML解析器能够解析复杂的XML文件,如问题中的那个。
Solved the issue. Used the org.json.XML toJsonObject function to convert XML to JSON. This XML parser is capable of parsing complex XML files like the one in the question.
这篇关于Jackson XmlMapper XML到Json的转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!