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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.