Search code examples
jsonxmlorg.json

Why am I getting invalide XML from JSON?


Here is my code (json is a String):

String xml = XML.toString(new JSONObject(json));

JSON:

{
    "components": {
        "header": "generic",
        "body": "generic",
        "footer": "watchlist"
    },
    "featuredArticle": {
        "title": "Test title",
        "text": "test text."
    },
    "header": {
        "ref": ""
    },
    "body": {
        "ref": ""
    },
    "footer": {
        "ref": ""
    }
}

XML:

<components>
    <footer>watchlist</footer>
    <header>generic</header>
    <body>generic</body>
</components>
<footer>
    <ref />
</footer>
<header>
    <ref />
</header>
<featuredArticle>
    <text>test text.</text>
    <title>Test title</title>
</featuredArticle>
<body>
    <ref />
</body>

When I validate the JSON in text mate it passes, but the XML does not.


Solution

  • A valid XML must have a root element. Your example does not have one.

    Try the following JSON (added root element "data"):

    {
        "data": {
            "components": {
                "header": "generic",
                "body": "generic",
                "footer": "watchlist"
            },
            "featuredArticle": {
                "title": "Test title",
                "text": "test text."
            },
            "header": {
                "ref": ""
            },
            "body": {
                "ref": ""
            },
            "footer": {
                "ref": ""
            }
        }
    }