It's maybe one of the most common tasks to implement a web API that returns a JSON in a software project. After you get the text response from your API, you would need to parse the JSON.

In Kotlin (and in Java), one of the easiest ways to do this is to use a library like Gson:

val model = gson.fromJson(textResponse, Model::class.java)

This will parse the JSON response and instantiate a class with the appropriate values. But to fill the object with the appropriate values, the class should resemble the JSON structure of the response.

Update: GSON is not recommended anymore (ref). One alternative is to use Kotlin JSON serialization:

The model in Kotlin could be a data class. This is super easy to declare. You just define the class properties and Kotlin takes care of the rest.

For instance, for a simple JSON such as:

{ "info": { "message": "OK", "records": 1, "current_page": 1, "page_size": 1000 } }

you would need a data class declaration:

data class Model( val info: Info, ) { data class Info( val current_page: Int, val message: String, val page_size: Int, val records: Int ) }

This quite simple and doable by hand. The complexity arises when the JSON response is way more complicated. And in real-world, (almost) all the JSON responses from an API are long and complicated.

Thankfully some tools take the raw JSON text and create a data class declaration for us!

For the frequent user

If you are going to be needing this functionality a lot, this IntelliJ (Android studio compatible) plugin, JsonToKotlinClass, is all you need. It can create Kotlin data classes with all kinds of customizations (such as inner or one-class-per-file classes, special annotations, etc) right from the IDE.

This is an open-source project with over 1.5k stars, at the time of writing.

For the casual user

If you only need this functionality occasionally, you can try Json2Kotlin.com. Simple but super-useful, you just enter the raw JSON and you get back a data class declaration. Not many customization options, but if you are looking for a quick conversion, this is your tool.

Validation

Huge JSON text is hard to parse manually and harder to detect if it's a valid JSON. The tools above will refuse to create a class declaration for an invalid JSON. So if you encounter any problems (such as disabled buttons in JsonToKotlinClass), validate your JSON first and try again.

Happy API implementations!