Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert XML to JSON in Java with child nodes as array

Tags:

java

json

xml

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"]
      }]
   }
}
like image 224
Etan Grundstein Avatar asked Sep 21 '16 09:09

Etan Grundstein


1 Answers

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"
}
like image 98
Valentyn Kolesnikov Avatar answered Oct 20 '22 09:10

Valentyn Kolesnikov