4

I am trying to convert a xml to json string using the below function

JSONObject org.json.XML.toJSONObject(String xmlstring)

The issue is this function cant differentiate between a collection list and a object. For eg say

I convert the following

Case1

xml:

<Book>  
    <Topic>1</Topic> 
</Book> 

json:

{
  "Book": {
    "Topic": "1"
  }
}

Case2

xml:

<Book>  
    <Topic>1</Topic> 
    <Topic>2</Topic> 
</Book> 

Json:

{
  "Book": {
    "Topic": [
      "1",
      "2"
    ]
  }
}

The xml format in both cases are the same but the json results aren't the same. If you notice in case1 the Topic equals an object whereas in case2 Topic equals a array of objects.

The function declaration clearly says Some information may be lost in this transformation because JSON is a data format and XML is a document format.

Is this a result of the data loss from xml to json? How can I get the result in case1 as

{
  "Book": {
    "Topic": [
      "1"
    ]
  }
}
3

0

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.