Java XML to JSON using XMLSerializer making root element an Array

AcidHawk :

Given that I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <op>update</op>
    <path>someString</path>
    <value>12345</value>
</Root>

and I want this output in JSON:

[{ "op":"update", "path":"someString", "value":"12345" }]

I have tried the following code:

package jsonconvertor;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

public class JSONConvertor {

    public static void main(String[] args) {

        String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root><op>update</op><path>someString</path><value>12345</value></Root>";
        String output = "";

        XMLSerializer xml = new XMLSerializer();
        JSON jObj = xml.read( input );
        output = jObj.toString();

        System.out.println("My JSON:\n" + output);
    }
}

When I run that code I get the following response:

{"op":"update","path":"someString","value":"12345"}

However you will notice that the leading '[' and closing ']' are missing.

When I try changing the XML "input" string in the code to the following:

String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root class=\"object\"><op>update</op><path>someString</path><value>12345</value></Root>";

which makes sense since itRoot was an object to start with, so I tried changing the "input" string to "array":

String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root class=\"array\"><op>update</op><path>someString</path><value>12345</value></Root>";

however then I get the following:

["update","someString","12345"]

What am I missing? I want the output I get when class="object" however I want it enclosed in square brackets. I want the output to look like the example at the top of the post.

apandey846 :

Try with this input String it should work :

String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root class=\"array\"><SubRoot class=\"object\"><op>update</op><path>someString</path><value>12345</value></SubRoot></Root>";

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107109&siteId=1