I have to convert xml string to json object using java, this is very a common requirement , for which I have used below code which works very fine
content = "<books>
<science>
<name>volcano</name>
</science>
<science>
<name>gravity</name>
</science>
</books>"
JSONObject xmlJSONObj = XML.toJSONObject(content);
String jsonPrintString = xmlJSONObj.toString();
System.out.println(jsonPrintString);
output looks like:
{
"books": {
"science": [
{ "name": "volcano" },
{ "name": "gravity" }
]
}
}
now suppose my input content string is like the below one
<books>
<science>
<name>volcano</name>
</science>
</books>
I still require output as
{
"books": {
"science" : [
{ "name" : "volcano" }
]
}
}
where the element science is still represented as list , as I need to feed this json as input to a tool which needs the element science as a list else if output is as
{
"books": {
"science": { "name": "volcano" }
}
}
it fails as science is not a list. Please provide me some tips on this. Thanks in advance.