2

This is my json value:

{
    "hello": [
        {
            "names": {
                "name": "abc"
            }
        },
        {
            "names": {
                "name": "def"
            }
        }
    ]
}

I tried using XML.toString(new JsonObject()), and this is what I get:

   <hello>
       <names>
          <name>abc</name>
       </names>
   </hello>
   <hello>
       <names>
          <name>def</name>
       </names>
   </hello>

Whereas, the xml I expected was this:

   <hello>
       <names>
          <name>abc</name>
       </names>
       <names>
          <name>def</name>
       </names>
   </hello>

This unexpected behaviour results in an invalid XML error, since there is no root element now. What am I missing here?

3
  • you mean XML.toString(new JsonObject())? Commented Nov 1, 2015 at 17:35
  • @Rehman: There is no other significant piece of code than just XML.toString(new JSONObject(string)). Commented Nov 1, 2015 at 17:40
  • @ᴳᵁᴵᴰᴼ: Edited the question. Thanks! Commented Nov 1, 2015 at 17:46

1 Answer 1

3

The issue in your JSON code. The [] means array, and by definition array is a set of elements. So the resulting xml code contains a set of hello elements. Try change your [] with {}:

{
    "hello": {
        "names": [
            {
                "name": "abc"
            },
            {
                "name": "def"
            }
        ]
    }
}

Just tried it and got the exact output you're looking for:

<hello>
    <names>
        <name>abc</name>
    </names>
    <names>
        <name>def</name>
    </names>
</hello>
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.