How to convert a single XML Object to JSONArray in Java

462 Views Asked by At

I am working on a solution to convert XML into JSON. Here I am facing an issue in which sometimes a node in XML comes as an object vs sometimes as an array. When a single node is found then it gets converted to single JSON object and array forms same JSON array.

The problem comes when I need to fill a Java bean with the converted JSON and I can define the node in bean class either as a single object or List of object.

Dependencies used:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

XML body (with multiple objects):

<SearchAccountResult>
    <ReponseXML>
         <Result>
            <MatchResult></MatchResult>
            <MatchResult></MatchResult>
            <MatchResult></MatchResult>
        </Result>
  </ReponseXML>
</SearchAccountResult>

JSON conversion of above XML:

{
 "Response":OK,
 "Errors":"",
 "ReponseXML":{
    "Result":[{},{},{}]   //CREATE AN ARRAY OF MatchResult DATA
  }
}

XML body (with single object):

<SearchAccountResult>
    <ReponseXML>
         <Result>
            <MatchResult></MatchResult>
        </Result>
  </ReponseXML>
</SearchAccountResult>

JSON conversion of above XML:

{
 "Response":OK,
 "Errors":"",
 "ReponseXML":{
    "Result":{}   //CREATES AN OBJECT WITH MATCHRESULT DATA
  }
}

The desired output I want should be:

{
 "Response":OK,
 "Errors":"",
 "ReponseXML":{
    "Result":[{}]   //JSON ARRAY WITH SINGLE OBJECT
  }
}

Code of conversion:

JSONObject companyDetailJson = XML.toJSONObject(responseXML);
0

There are 0 best solutions below