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?