Jackson XmlMapper XML to Json conversion issue

1.2k Views Asked by At

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);

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"
}

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?

Thanks!

1

There are 1 best solutions below

0
On

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.