Converting XML to JSON with variable item size

156 Views Asked by At

For our project , we sometimes get a list of array of pans, sometimes a single pan . We are converting the below to json on the fly using the org.json library and consuming in some java application. XML :

  <item>
  <b type="playlist">Pan1a</b>
  </item>

  <item>
  <b type="clip">Pan2a</b>
  <b type="clip">Pan2b</b>
  </item>

  JSON 

  {
    "item": {
      "b": {
        "-type": "playlist",
        "#text": "Pan1a"
      }
    }
  }


  {
    "item": {
      "b": [
        {
          "-type": "clip",
          "#text": "Pan2a"
        },
        {
          "-type": "clip",
          "#text": "Pan2b"
        }
      ]
    }
  }

The issue is , if the item has more than 1 objects the json is giving ArrayList [] , but if the number of objects =1 then giving single Object and not Array with size 1. As a result we are unable to parse the json at the endpoint as pojo need to be defined first. What is the best way to make the xml give json as below with size 1 only.

  {
   "item": {
     "b": [{
       "-type": "playlist",
       "#text": "Pan1a"
     }]
   }
 }
0

There are 0 best solutions below