How to parse JSON in Kotlin Android?

This kotlin json parser example using gson discusses following points:
1)  Convert a data class in Kotlin to JSON string using Gson Java library
2)  How to parse JSON String to a Data Model Class / Kotlin bean

MainActivity.kt
package com.example.espl.parsejsoninkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.gson.Gson

class MainActivity : AppCompatActivity() {
//The TestModelClass with 3 attributes: id name and city. So, the JSON string would be as below
    val JSON_STRING: String ="{\"id\":1,\"name\":ram,\"city\":\"AMD\"}"

    // initialise gson var
    var gson = Gson()

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

    //Convert from JSON String to a Data Model Class object
        var testModel = gson.fromJson(JSON_STRING, TestModelClass::class.java)
        Log.e("testModel:City","::"+testModel.city)

        //Convert to JSON String from Data Model Class
        val jsonString = gson.toJson(TestModelClass(1,"Navu","KLKT"))
        Log.e("jsonString:","fromModelClass::"+jsonString)
    }

// Create a data class TestModelClass which Convert json string data to Kotlin Bean
// Also, use to convert a data class in Kotlin to JSON string
  data class TestModelClass(
        val id: Int,
        val name: String,
        val city: String
    )
}

build.gradle (Module:app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.espl.parsejsoninkotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

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

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

No comments:

Post a Comment

Popular Posts