Read this documentation about Serialize Xml Node

You can force JSON Array this way

var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >
             <Item json:Array='true'>
                <Name>name</Name>
                 <Detail>detail</Detail>    
            </Item>
            </Items>";

DEMO

Answer from meda on Stack Overflow
Discussions

Having issue while convertnig xml with single element to json array or vice versa
Please have a look at - http://stackoverflow.com/questions/42900503/json-xml-converter-having-array-in-json-string/42901710#42901710 More on github.com
🌐 github.com
25
March 20, 2017
[XmlToJson] Single Element to JSON array Error | OutSystems
I've been encountering this problem where an element from the Xml can either have one or more items inside it, so when I convert it into Json: · One item translates to { "name" : "value" } while multiple items translate to [ { "name" : "value" } ] More on outsystems.com
🌐 outsystems.com
jquery - Convert XML to JSON (and back) using Javascript - Stack Overflow
In my case, the JSON is the canonical representation, and XML is just used for XSLT.. the use of which is not my idea! :) 2009-11-20T23:29:33.96Z+00:00 ... This is only in the browser. Doesn't apply for node.js or non-browser environments. Any other ideas? 2013-05-02T17:47:45.953Z+00:00 ... In regards to @JasonDenizac comment to his post, I am not sure to understand how this link helps fixing the issue of having an object instead of an array of one ... More on stackoverflow.com
🌐 stackoverflow.com
java - Process single element array when converting XML to JSON ( ) - Stack Overflow
But the org.json library cannot detect this. It can detect only if there are multiple elements. My question is, is there a library that I can use to detect a single element array using the available tag in the XML string? More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › stleary › JSON-java › issues › 330
Having issue while convertnig xml with single element to json array or vice versa · Issue #330 · stleary/JSON-java
March 20, 2017 - but, we need similar behavior while converting json to xml and back again where json array is having single element i.e. input json - {"readResult": {"errors": [{"code": 400}]}} converted xml - <readResult><errors><code>400</code></errors></readResult> output json - {"readResult":{"errors":{"code":400}}} ... You can’t perform that action at this time.
Author   rvashishth
🌐
OutSystems
outsystems.com › forums › discussion › 82490 › xmltojson-single-element-to-json-array-error
[XmlToJson] Single Element to JSON array Error | OutSystems
I've been encountering this problem where an element from the Xml can either have one or more items inside it, so when I convert it into Json: · One item translates to { "name" : "value" } while multiple items translate to [ { "name" : "value" } ]
🌐
Newtonsoft
newtonsoft.com › json › help › html › ConvertXmlToJsonForceArray.htm
Convert XML to JSON and force array
string xml = @"<person id='1'> <name>Alan</name> <url>http://www.google.com</url> <role>Admin1</role> </person>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": "Admin1" // } // } xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'> <name>Alan</name> <url>http://www.google.com</url> <role json:Array='true'>Admin</role> </person>"; doc = new XmlDocument(); doc.LoadXml(xml); json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": [ // "Admin" // ] // } // }
🌐
Cloud-elements
docs.cloud-elements.com › home › convert-xml-repeated-elements-json-array
Convert an XML with Repeated Elements to a JSON Array | Cloud Elements Help Center
March 23, 2020 - Shown below is a sample XML response ... the XML into a JSON array with multiple objects. However, if the XML contains only one repeated element, the JSON converter converts the XML into an object instead of an array....
Find elsewhere
🌐
Iditect
iditect.com › faq › csharp › convert-xml-to-json-array-when-only-one-object-in-c.html
Convert XML to Json Array when only one object in C#
Otherwise, the XML string is loaded into an XmlDocument object, and the Deserialize method is called to convert the first element to an XmlNode object. The CanConvert method is overridden to return true if the type being serialized is an XmlNode. Finally, the JsonConvert.SerializeObject method is called with an array of XML nodes containing the one XmlNode object from the XML string.
🌐
Stack Overflow
stackoverflow.com › questions › 69938927 › process-single-element-array-when-converting-xml-to-json-xml-multiple
java - Process single element array when converting XML to JSON ( ) - Stack Overflow
<?xml version="1.0" encoding="UTF-8"?> <jsonObject> <data> <?xml-multiple accounts?> <accounts> <Id>123</Id> <creationDate>2021-10-21T15:43:00.12345Z</creationDate> <displayName>account_x</displayName> </accounts> </data> <links> <self>self</self> <first>first</first> <prev>prev</prev> <next>next</next> <last>last</last> </links> <meta> <totalRecords>10</totalRecords> <totalPages>10</totalPages> </meta> </jsonObject> Here, 'accounts' is an element of an array and contains only a single element.
Top answer
1 of 7
2

I'm late on this... but, using org.json:

public static void forceToJSONArray(JSONObject xmlJSONObj, String obj) throws org.json.JSONException 
{
    // where "JSONObject xmlJSONObj" is my JSONObject obtained by passing the XML throug the method toJSONObject 
    // and where "String obj" is the name of the JSONObject I want to force to JSONArray
    Object myObj = xmlJSONObj.opt(obj);
    if (myObj == null)
    {
        // if my obj doesn't exist inside my xmlJSONObj i create it empty
        JSONArray jsonArray = new JSONArray();
        xmlJSONObj.put(obj, jsonArray);
    }
    else if ( myObj instanceof JSONObject ) 
    {
        // if exist but is a JSONObject, I force it to JSONArray
        JSONObject myJSONObj = (JSONObject)myObj;
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(myJSONObj);
        xmlJSONObj.put(obj, jsonArray);
     }
     else if ( myObj instanceof String || myObj instanceof Integer ) 
     {
        // if exist but is a primitive entry (like in your case), I force it to a "primitive" JSONArray
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(myObj);
        xmlJSONObj.put(obj, jsonArray);
     }  
}

Hope this could help ;)

2 of 7
1

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);
🌐
GitHub
github.com › stleary › JSON-java › issues › 235
XML to json Array Issue · Issue #235 · stleary/JSON-java
June 2, 2016 - I need to parse a specific XML element of xml content, that has only one occurency, to a JSON Array object, using XML.toJSONObject(xml). How do this? When the XML element appears more than one occurence, it's work fine! ... You can’t perform that action at this time.
Author   smtrad
🌐
CopyProgramming
copyprogramming.com › howto › convert-xml-to-json-array-when-only-one-object-java
Java: Java: Converting XML to Json Array for Single Object
April 29, 2023 - And we want this JSON: { "person":{ "name":"Tony", "data":{ "car":["Toyota"] } } } The method's invocation should be in this format. forceToJSONArray(xmlJSONObj, Arrays.asList("person", "data", "car"), 0); Solution 3: In case an XML tag contains only one child, it will be transformed into an object...
🌐
Microsoft Power Platform Community
powerusers.microsoft.com › t5 › Building-Flows › Force-array-format-when-converting-XML-to-JSON › td-p › 1371314
Force array format when converting XML to JSON
December 2, 2021 - Quickly search for answers, join discussions, post questions, and work smarter in your business applications by joining the Microsoft Dynamics 365 Community.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-xml-to-json-array-in-java
How to convert XML to JSON array in Java?
Gson is a third-party Java library developed by Google. It is used for converting Java objects to JSON and vice versa. To know more about Gson, refer to the Gson tutorial. We can use the Gson class of the Gson library to convert XML to JSON. The Gson class is a subclass of JsonElement class.
🌐
Medium
medium.com › @mbearz › strange-c-tricks-9-xml-to-json-using-jsonschema-6e4577c05852
Strange C# Tricks 9: XML to JSON using JsonSchema. | by Michael Berezin | Medium
February 22, 2024 - For arrays (see the “tags” section) we have a type for the properties and an “items” section that tells us the type of the object in the array · Note about array items and C# Technically we can create JSON that has an array that contains different types ... For this array, the items will have several types. If a JSON array has an item from the same type the items section in the schema will only have 1 type.
🌐
Stack Overflow
stackoverflow.com › questions › 61323686 › convert-xml-to-json-array-when-only-one-object-is-available-using-java
Convert XML to JSON Array when only one object is available using Java - Stack Overflow
April 20, 2020 - Note - In case multiple objects are available, I'm getting Array as expected. ... import org.json.JSONObject; import org.json.XML; public class Convert { public static void main(String[] args) { String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<School >" + "<Class>II-B</Class>" + "</School>"; try { JSONObject jsonObj = XML.toJSONObject(xmlString); String json = jsonObj.toString(4); System.out.println(json); } catch (Exception e) { // TODO: handle exception } } }