Reputation: 267
I need to convert XML into JSON and I have the following code which works fine. The problem, however, arises when an XML element should actually be converted into an array. My question is in two parts:
1) What is the proper way to represent an array in xml?
Here is the xml I'm currently using. The contents of elements should actually be an array. So elements[0] should be the element within.
<project id="200">
<name>test</name>
<elements>
<element>
<id>body</id>
<width>200</width>
<height>400</height>
<children/>
</element>
</elements>
</project>
2) How can I convert the xml into JSON containing JSON arrays as well as objects?
private String xmlToJson(String xml) throws IOException {
JSONObject jsonObject = XML.toJSONObject(xml);
return jsonObject.toString(4);
} // End of XML to JSON
Many thanks
Upvotes: 4
Views: 7328
Reputation: 2097
There is an underscore-java library with static method U.xmlToJson(xml)
. It supports a special attribute array="true" which forces the element to be an array.
<project id="200">
<name>test</name>
<elements>
<element array="true">
<id>body</id>
<width>200</width>
<height>400</height>
<children/>
</element>
</elements>
</project>
Output:
{
"project": {
"-id": "200",
"name": "test",
"elements": [
{
"id": "body",
"width": "200",
"height": "400",
"children": {
"-self-closing": "true"
}
}
]
},
"#omit-xml-declaration": "yes"
}
Upvotes: 1
Reputation: 23351
Answering your 1st question: What is the proper way to represent an array in xml?
Please refere to: http://www.w3.org/2005/07/xml-schema-patterns.html#Vector
Upvotes: 0