1

I'm trying to convert XML to JSON using the org.JSON library. However, when there is only one element in XML, it's unable to convert the element as an Array.

source.xml

<users>
    <user>user1</user>
</users>

Code for conversion:

File xml= new File("src/main/resources/xml/source.xml");

String data = FileUtils.readFileToString(xmlFile, "UTF-8");

String value = XML.toJSONObject(data).toString();

Output:

{
    "users": {
        "user": "user1"
    }
}

I tried with multiple options,

like

  <users>
        <?xml-multiple?>
        <user>user1</user>
    </users>

Output:

 {"users":{"user":"user1"}}

and with json:Array='true'

<users>
    <user json:Array='true'>user1</user>
</users>

Output:

  {"users":{"user":{"json:Array":true,"content":"user1"}}}

and nothing seems to be working. I've tried with fasterxml and unxml libraries as well.

Expected output:

{
    "users": {
        "user": ["user1"]
    }
}

Is there any library or a way to do this in Java?

Erik
  • 503
  • 1
  • 7
  • 26
  • Are you sure that it is that you want? Because the expected output you waiting means there can be a user with different usernames like user1,user2 etc. It will be the names for the only one user itself. – Akiner Alkan Jan 16 '19 at 12:59
  • Yes, I need it in the format specified in question. I have given a sample format to explain the problem, but the object properties are different. Please let me know if you need any further clarification on the question. – user5245939 Jan 17 '19 at 04:56
  • You need to have a `Users` class and `user` field in it. That `user` field should be declared as `array`. Then you need to deserialize xml to that `Users` object. After that when you serialize that object to JSON it will work as you wanted – Akiner Alkan Jan 17 '19 at 07:51

0 Answers0