Skip to main content

The “JSON To Kotlin Data Class”-Plugin

·2 mins

Create a Kotlin data class from JSON code automatically. #

This post describes how to use a plugin called “JSON To Kotlin Class” that automatically creates a Kotlin data class from JSON code in Android Studio.

Imagine you have a piece of JSON code that you need to send or receive from a REST service, for example. Depending on the JSON’s length, it can be cumbersome to manually create a Kotlin data class from it.

Wouldn’t it be nice to have a way to automatically create a new class from this JSON code? Unfortunately, when opening the “New” dialog in Android Studio, it only provides the usual options.

Wouldn’t it be nice to have an option that does what we want: take a JSON and create the data class for it?

Luckily, there are plugins that can help us achieve this. To get started, go to “Settings → Plugins.”

To install “JSON to Kotlin Class,” search for “JSON” and select the “JSON To Kotlin Class” plugin. Then, press “OK.”

If you want to create a Kotlin data class, there is a new menu entry for creating one from JSON.

Selecting it opens a window.

Please provide a class name and paste JSON into the field below.

Click on “Generate” and then examine the source file.

package com.example.apod

data class ApodDto(
    val date: String,
    val explanation: String,
    val hdurl: String,
    val media_type: String,
    val service_version: String,
    val title: String,
    val url: String
)

What do you think? This saves a lot of work, doesn’t it?

Thank you for reading!

https://twissmueller.medium.com/membership

Resources #