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
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
Post a Comment