Reputation: 59
I am using org.json to convert an xml to json using below code snippet.Unfotunately, there is a structure called "countries" which is supposed to be an array, but can have only 1 country sometimes. In such cases, array is not getting disaplyed instead "countries" is showing up under {} instead of [{}] or [].
JSONObject xmlJSONObj = XML.toJSONObject(xsltresponse);
return xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
output i am getting is with after json conversion is:
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":{
"name:"AN"
}}}
Instead of getting below output
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":[{
"name:"AN"
}]
}}
How do i fix it?
Upvotes: 2
Views: 3297
Reputation: 59
I used this to arrive at solution, this works fine. I will mark it as accepted answer. Please let me know other wise.
JSONObject xmlJSONObj = XML.toJSONObject(response);
JSONArray jsonArray = new JSONArray();
JSONObject data = xmlJSONObj.getJSONObject("data");
JSONObject objArr = data.optJSONObject("countries");
if (objArr != null) {
jsonArray.put(objArr);
data.putOpt("countries", jsonArray);
}
Upvotes: 1