In this quick article, we’ll see how to convert XML to JSON in Kotlin.

Kotlin didn’t provide any capability to convert XML to JSON. However, you can use the JSON in Java library for quick conversion between JSON and XML.

The idea is to use the static XML.toJSONObject() method from the org.json package to convert the XML to JSON Object. To get the string representation of the JSON object, you can call the toString() method on it. Following is a simple example demonstrating usage of this.

Download Code

 
Output:

{"catalog": {"book": [
    {
        "author": "Bruce Eckel",
        "genre": "Computer",
        "id": "kotlin1",
        "pages": 636,
        "published": "November 2021",
        "title": "Atomic Kotlin"
    },
    {
        "author": "Dmitry Jemerov and Svetlana Isakova",
        "genre": "Computer",
        "id": "kotlin2",
        "pages": 532,
        "published": "3 February 2017",
        "title": "Kotlin in Action"
    },
    {
        "author": "Dawn Griffiths, David Griffiths",
        "genre": "Computer",
        "id": "kotlin3",
        "pages": 814,
        "published": "13 February 2019",
        "title": "Head First Kotlin"
    },
    {
        "author": "Josh Skeen, David Greenhalgh",
        "genre": "Computer",
        "id": "kotlin4",
        "pages": 532,
        "published": 2018,
        "title": "Kotlin Programming: The Big Nerd Ranch Guide"
    },
    {
        "author": "Venkat Subramaniam",
        "genre": "Computer",
        "id": "kotlin5",
        "pages": 462,
        "published": "20 September 2019",
        "title": "Programming Kotlin"
    },
    {
        "author": "Pierre Yves Saumont",
        "genre": "Computer",
        "id": "kotlin6",
        "pages": 674,
        "published": "21 April 2019",
        "title": "The Joy of Kotlin"
    }
]}}

That’s all about converting XML to JSON in Kotlin.

 
Also See: Convert XML to JSON online