0

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.

Judge Mental
  • 5,209
  • 17
  • 22
sabah_21
  • 1
  • 1
  • Possible duplicate [toJSONObject() in Java doesnt differentiate list of objects and object. Is this a result of the information loss during the conversion?](http://stackoverflow.com/questions/20975961/tojsonobject-in-java-doesnt-differentiate-list-of-objects-and-object-is-this) – Ivo Mori Jan 05 '16 at 20:34

1 Answers1

0

This is not a Java problem, but an XML problem. Given just the input XML data the converter cannot determine if the 'science' element is a single or multiple value. The above code is not wrong. It just doesn't have enough information and consequently does the wrong assumption. What is needed is a definition of the structure of these documents. A DTD or an XML Schema definition. Once you have such a definition you can even use more sophisticated approaches like JAXB to properly parse the XML. Serializing to JSON would then be a piece of cake.

Rudi Angela
  • 1,463
  • 1
  • 12
  • 20