首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Json XmlMapper XML到Json的转换问题

Json XmlMapper XML到Json的转换问题
EN

Stack Overflow用户
提问于 2016-01-19 17:02:37
回答 1查看 1K关注 0票数 0

我使用Jackson XmlMapper读取XML字符串并将其转换为JsonString。我的XML文件是:

代码语言:javascript
复制
<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>

我为转换编写的代码是:

代码语言:javascript
复制
XmlMapper xmlMapper = new XmlMapper();
List entries = xmlMapper.readValue(file, List.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(entries);

我得到的作为输出的Json字符串是:

代码语言:javascript
复制
{
  "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表示。我该如何处理这个问题?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2016-02-04 11:49:05

解决了问题。使用org.json.XML toJsonObject函数将XML转换为JSON。这个XML解析器能够解析复杂的XML文件,就像问题中提到的那样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34872489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档