1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.