Based on Mario's solution, I made some changes, specially for nested children in the Json object. The xmlJSONObj is the same, but the obj param is a List that contains the path to the JSON child, and the index param is only required for the recursion (it should start at 0 in the first execution).
/**
* Forces a JSON Object to be an Array. When converting from XML to JSON, There may be cases in
* which we want a list of elements in the final JSON but there is only one element in the XML
* file, so the XML.toJSONObject method will fail. This methods forces a JSON element to be an
* array instead of just a JSON Object.
*
* @param xmlJSONObj obtained by passing the XML through the method toJSONObject
* @param obj list of String that contains the path to the JSON child to convert to Array
* @param index required for recursion, starts at 0
* @throws org.json.JSONException
*/
public static void forceToJSONArray(JSONObject xmlJSONObj, List<String> obj, int index)
throws org.json.JSONException {
Object myObj = xmlJSONObj.opt(obj.get(index));
if (myObj instanceof JSONObject && obj.size() == index + 1) {
JSONObject myJSONObj = (JSONObject) myObj;
JSONArray jsonArray = new JSONArray();
jsonArray.add(myJSONObj);
xmlJSONObj.put(obj.get(index), jsonArray);
} else if (myObj instanceof JSONObject) {
forceToJSONArray((JSONObject) myObj, obj, index + 1);
}
}
Example:
We have this JSON:
{
"person":{
"name":"Tony",
"data":{
"car":"Toyota"
}
}
}
And we want this JSON:
{
"person":{
"name":"Tony",
"data":{
"car":["Toyota"]
}
}
}
We should call the method like this:
forceToJSONArray(xmlJSONObj, Arrays.asList("person", "data", "car"), 0);