Android Kotlin GSON To ( Model > JSON)

In the previous of tutorial we have seen using GSON Library parsing From JSON To Model/Data  class , in this tutorial we will see reverse of it i.e from Model/Data to JSON .

Gradle

Add GSON dependency to app level build.gradle file

dependencies {
    ............
 ............
    implementation 'com.google.code.gson:gson:2.8.5'
}

Simple JSON


Model

file : Model.kt
package com.tutorialsbuzz.androifromgson

import com.google.gson.annotations.SerializedName

data class Model(
    @SerializedName("name") val name: String,
    @SerializedName("age") val age: Int
) {}


private fun toJSONSimpleJSON(): Unit {
        val model = Model("John", 29)
        val gson = Gson()
        Log.d("ToJSONSimpleJSON : ", gson.toJson(model));
    }

log-cat
2019-08-31 16:23:33.247 14905-14905/com.tutorialsbuzz.androifromgson D/ToJSONSimpleJSON :: {"age":29,"name":"John"}

ArrayOfJSONObject


Model

file :country.kt
package com.tutorialsbuzz.androifromgson

import com.google.gson.annotations.SerializedName

data class Country(
    @SerializedName("name") val name: String,
    @SerializedName("capital") val capital: String
) {}


private fun toJSONArrayOfJSON(): Unit {
        val countryList: MutableList<Country> = mutableListOf<Country>()

        countryList.add(Country("India", "Delhi"))
        countryList.add(Country("United States of America", "Washington D C"))
        countryList.add(Country("United Kingdom", "London"))
        countryList.add(Country("Australia", "Canbera"))
        countryList.add(Country("France", "Paris"))
        countryList.add(Country("Australia", "Canbera"))
        countryList.add(Country("Germany", "Berlin"))
        countryList.add(Country("Russia", "Moscow"))
        countryList.add(Country("Sweden", "Stockholm"))

        val gson = Gson()

        Log.d("ToJSONArrayOfJSON : ", gson.toJson(countryList));
    }

log-cat
2019-08-31 16:24:12.552 15074-15074/com.tutorialsbuzz.androifromgson D/ToJSONArrayOfJSON :: [{"capital":"Delhi","name":"India"},{"capital":"Washington D C","name":"United States of America"},{"capital":"London","name":"United Kingdom"},{"capital":"Canbera","name":"Australia"},{"capital":"Paris","name":"France"},{"capital":"Canbera","name":"Australia"},{"capital":"Berlin","name":"Germany"},{"capital":"Moscow","name":"Russia"},{"capital":"Stockholm","name":"Sweden"}]


No comments:

Post a Comment