Generate Kotlin Data class from Json using JsonToKotlin Class Plugin

J KJ K
2 min read

Json to Kotlin Data Class using JsonToKotlinClass plugin

While we integrate API, We have to create Kotlin classes. I am sure most of you search on google “Json to Kotlin class generate online” or For Simple JSON data, you have created Kotlin Classes manually.

We need someone to do this tedious task for us. Here we have JsonToKotlin Class plugin for it.

JsonToKotlinClass is a plugin to create Kotlin data classes from JSON.

Supporting all kinds of JSON libs’ annotation(Gson, Jackson, Fastjson, Moshi and LoganSquare, kotlinx.serialization).

if you want to read more about plugin features: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

Now we will follow two steps to generate Kotlin data class from JSON:
Step 1: Install JsonToKotlinClass Plugin in Android Studio
Step 2: Convert JSON data into Kotlin Class

Let’s start.

Step 1: Install JsonToKotlinClass Plugin

  • Open the Preferences window by clicking File > Settings (on Mac, Android Studio > Preferences).

  • Click on Plugins

  • Select MarketPlace and Search “JsonToKotlin”
  • Click ‘ Install
  • Click Apply and Ok to save your changes

Follow Above Steps to Install JsonToKotlinClass Plugin

Step 2: Convert JSON data into Kotlin Class

Now it’s time to generate Kotlin Data classes from JSON. Here I use

JSONPlaceholder API, JSONPlaceholder is a free online REST API.

  • Select the Project section, then right-click on that folder and select New > Kotlin data class file from JSON (as shown in the image below).

  • In Generate Kotlin Data Class Code Dialog, Past JSON String in Blank Area and give Class name “TodoList” and click Generate.

Past Json and click generate

  • We can see two files generated as shown in the image below.

Two files were generated

  • Customize the Advance feature as below

  • In Property, select the Val keyword and select Type Non-nullable.

  • In Annotation, select Gson.
  • In Extensions, select Add Gson @Expose Annotation.

Apply the above features to the below JSON:

UserItem JSON String

Three files were generated as the below image:

UserItem, Address and Geo Class were Generated

That’s it.

Thanks for spending your time reading this article. 👏 and share if you’ve enjoyed it.

8
Subscribe to my newsletter

Read articles from J K directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

J K
J K