Skip to main content

Simplify Your Tax Calculations with GST Calculator 2024: The Ultimate Tool for Businesses and Individuals

Convert JSON to Kotlin Model class Using GSON, in 5 seconds, Android | Kotlin

 As a Native android developer, it is very difficult to parse a complex JSON in our application. Normally the rest api json structure is much complex to parse it using functions as getObject(), getString(), getBoolean() etc.

So, In order to overcome this problem also for save time we use GSON. Many developers already know that, but here I give you a simple and short solution that, you can convert JSON to Kotlin Model class for any complex JSON within 5 seconds. So Just follow the guidelines-

Okay, First you can add the gradle dependency of GSON

implementation 'com.google.code.gson:gson:2.8.6'


Now I can take a sample JSON, which I make model class and then parse. Below I mentioned the sample json-

{
  "problems": [
    {
      "Diabetes": [
        {
          "medications": [
            {
              "medicationsClasses": [
                {
                  "className": [
                    {
                      "associatedDrug": [
                        {
                          "name": "asprin",
                          "dose": "",
                          "strength": "500 mg"
                        }
                      ],
                      "associatedDrug2": [
                        {
                          "name": "somethingElse",
                          "dose": "",
                          "strength": "500 mg"
                        }
                      ]
                    }
                  ],
                  "className2": [
                    {
                      "associatedDrug": [
                        {
                          "name": "asprin",
                          "dose": "",
                          "strength": "500 mg"
                        }
                      ],
                      "associatedDrug2": [
                        {
                          "name": "somethingElse",
                          "dose": "",
                          "strength": "500 mg"
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ],
          "labs": [
            {
              "missing_field": "missing_value"
            }
          ]
        }
      ],
      "Asthma": [
        {
          
        }
      ]
    }
  ]
}


Now, Open Android Studio and create a project. 

Now open File->Settings->Plugins and search "JSON to Kotlin Class". Install the plugin and restart your android studio.


Now Simply you can open your project and create a kotlin class, sat 'JsonResponse.kt'. Now open the class and use "Alt +K" and a popup is opened. Now you can paste your JSON in this Form and set name "Response"


Now click on "Advance" button and set the setting as per below screenshots

Setting Property


Setting Annotation



Setting Others



Setting Extensions


Now click on OK, and in first pop-up click "Generate". Now your Kotlin class is ready.

it is your generated class

package com.example.adaptermaker

import androidx.annotation.Keep

import com.google.gson.annotations.SerializedName


class JsonResponse {

    @Keep
    data class Response(
        @SerializedName("problems")
        val problems: List<Problem>
    )

    @Keep
    data class Problem(
        @SerializedName("Asthma")
        val asthma: List<Asthma>,
        @SerializedName("Diabetes")
        val diabetes: List<Diabete>
    )

    @Keep
    class Asthma

    @Keep
    data class Diabete(
        @SerializedName("labs")
        val labs: List<Lab>,
        @SerializedName("medications")
        val medications: List<Medication>
    )

    @Keep
    data class Lab(
        @SerializedName("missing_field")
        val missingField: String
    )

    @Keep
    data class Medication(
        @SerializedName("medicationsClasses")
        val medicationsClasses: List<MedicationsClasse>
    )

    @Keep
    data class MedicationsClasse(
        @SerializedName("className")
        val className: List<ClassName>,
        @SerializedName("className2")
        val className2: List<ClassName2>
    )

    @Keep
    data class ClassName(
        @SerializedName("associatedDrug")
        val associatedDrug: List<AssociatedDrug>,
        @SerializedName("associatedDrug2")
        val associatedDrug2: List<AssociatedDrug2>
    )

    @Keep
    data class ClassName2(
        @SerializedName("associatedDrug")
        val associatedDrug: List<AssociatedDrugX>,
        @SerializedName("associatedDrug2")
        val associatedDrug2: List<AssociatedDrug2X>
    )

    @Keep
    data class AssociatedDrug(
        @SerializedName("dose")
        val dose: String,
        @SerializedName("name")
        val name: String,
        @SerializedName("strength")
        val strength: String
    )

    @Keep
    data class AssociatedDrug2(
        @SerializedName("dose")
        val dose: String,
        @SerializedName("name")
        val name: String,
        @SerializedName("strength")
        val strength: String
    )

    @Keep
    data class AssociatedDrugX(
        @SerializedName("dose")
        val dose: String,
        @SerializedName("name")
        val name: String,
        @SerializedName("strength")
        val strength: String
    )

    @Keep
    data class AssociatedDrug2X(
        @SerializedName("dose")
        val dose: String,
        @SerializedName("name")
        val name: String,
        @SerializedName("strength")
        val strength: String
    )
}


Create a kotlin class, say MyJsonParser.kt and write the below code

package com.example.adaptermaker

import com.google.gson.Gson
import kotlin.reflect.KClass

class MyJsonParser {

    companion object {

        fun <T : Any> getObjectFromJson(jsonBody: String, classType: KClass<T>): T {
            return Gson().fromJson(jsonBody, classType.java)
        }

        fun Any?.convertJson() = Gson().toJson(this)

    }
}



mmmmmmmmmmmmmmmmmmmmmm

"getObjectFromJson" this function is used to convert JSON to Model Class and "convertJson" function is used it for reverse. i.e Model to JSON.


Finally, I show you my MainActivity that how to parse the json

MainActivity.kt

package com.example.adaptermaker

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.adaptermaker.MyJsonParser.Companion.convertJson
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


    private val sampleJson =
        """{"problems":[{"Diabetes":[{"medications":[{"medicationsClasses":[{"className":[{"associatedDrug":[{"name":"asprin","dose":"","strength":"500 mg"}],"associatedDrug2":[{"name":"somethingElse","dose":"","strength":"500 mg"}]}],"className2":[{"associatedDrug":[{"name":"asprin","dose":"","strength":"500 mg"}],"associatedDrug2":[{"name":"somethingElse","dose":"","strength":"500 mg"}]}]}]}],"labs":[{"missing_field":"missing_value"}]}],"Asthma":[{}]}]}"""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Convert Json to Model
        val mResponse = MyJsonParser.getObjectFromJson(sampleJson, JsonResponse.Response::class)

        btnParseJson.setOnClickListener {

            //Convert Json to Model


            //As per my sample json, suppose I want to fetch
            //Diabetes->medications->medicationsClasses->className->associatedDrug->name
            val drugName =
                mResponse.problems[0].diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

            Toast.makeText(this, drugName, Toast.LENGTH_SHORT).show()
        }


        btnConvertJson.setOnClickListener {

            //Convert Model to JSON
            val mJson = mResponse.convertJson()

            Toast.makeText(this, mJson, Toast.LENGTH_SHORT).show()
        }


    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnParseJson"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parse Json"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnConvertJson"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Convert Json"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnParseJson" />

</androidx.constraintlayout.widget.ConstraintLayout>


Json to Model Class

Model class to Json Convert


You can download full source code here




Thanks for reading, Subscribe my blog by your mail.

You can follow me on https://debabratantss.medium.com



Comments

Popular posts from this blog

How to Insert Multiple rows in a single db transaction in Android Room Database? | Android | Room DB

  To insert multiple rows into a Room database in Android, you can follow these steps: 1. Set up Room Database: First, make sure you have set up your Room database correctly in your Android project. Define your Entity class, create a Database class that extends RoomDatabase, and set up your DAO (Data Access Object) interface. 2. Create Entity Class: Define an Entity class that represents the data you want to insert into the database. For example: 1 2 3 4 5 6 7 8 9 @Entity (tableName = "my_table" ) public class MyEntity { @PrimaryKey (autoGenerate = true ) public int id; public String name; public int age; // Add other fields and getters/setters as needed } Create DAO: Create a DAO interface with a method to insert multiple rows. For example: 1 2 3 4 5 @Dao public interface MyEntityDao { @Insert void insertAll (List<MyEntity> entities); } Initialise Database and DAO: In your application code, create an insta

How to fetch Latitude, Longitude from address and vice-versa(address from Latitude, Longitude) using Google Geo coder SDK in android| Kotlin

 In this Android development related article, you will get a simple solution that, how to get address using Latitude, Longitude and vice-versa. i.e latitude, longitude from an address text. It is very easy and simple. Read full article and carefully follow all the steps. Here we use google Geocoder SDK. Okay, first we create an android project in kotlin and create an Activity say MainActivity.kt. Use the below code- Function get Latitude, Longitude from Address- fun getLatLngFromAddress (context: Context, mAddress: String): String { val coder = Geocoder(context) lateinit var address: List<Address> try { address = coder.getFromLocationName(mAddress, 5 ) if (address == null ) { return "Fail to find Lat,Lng" } val location = address[ 0 ] return " Latitude: ${location.latitude}\n Longitude: ${location.longitude}" } catch (e: Exception

Recycler View Like Google Play Store App | How to use SnapHelper Android, Kotlin

 If we see the google play store android app, we can see that the app list in horizontal recycler view hold a property that the first property hold always full visible or not visible, but a portion visible is not seeing. This property is snap property. In this article I show you how to use it in our own application. Basically we use two type of snap. Center Snap and start snap. I show you both here. So read full article here. The Key Moment code is here- For center snap you need to write 2 lines code- //center Snap val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(recyclerView1) For start snap, create a class in kotlin say StartSnapHelper.kt package com.example.snaphelpersampleapp import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView class StartSnapHelpe