I'm looking for a way to convert an XML to JSON in Java in a way such that child nodes will alway be converted to an array. In Node.js there's the library XmlToJs.
The use case is when I have an XML like the following:
XML:
<A>
<B>
<C>data</C>
</B>
<B>
<C>data1</C>
<C>data2</C>
</B>
</A>
JSON with org.json conversion:
{
"A": {
"B": [{
"C": "data"
}, {
"C": ["data1", "data2"]
}]
}
}
what I would like for the conversion to yield:
{
"A": {
"B": [{
"C": ["data"]
}, {
"C": ["data1", "data2"]
}]
}
}
You may try underscore-java library and static method U.xmlToJson(xml)
. There is a special attribute array="true"
which forces element to be an array. I am the maintainer of the project.
<A>
<B>
<C array="true">data</C>
</B>
<B>
<C>data1</C>
<C>data2</C>
</B>
</A>
Output:
{
"A": {
"B": [
{
"C": [
"data"
]
},
{
"C": [
"data1",
"data2"
]
}
]
},
"#omit-xml-declaration": "yes"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With