0
0
Android Kotlinmobile~5 mins

JSON parsing with Gson/Moshi in Android Kotlin

Choose your learning style9 modes available
Introduction

We use JSON parsing to convert text data from the internet into objects our app can understand and use easily.

When your app gets data from a web service in JSON format.
When you want to save app data as JSON and read it back later.
When you need to convert JSON strings into Kotlin objects to show on screen.
When you want to send data from your app to a server in JSON format.
Syntax
Android Kotlin
val gson = Gson()
val obj = gson.fromJson(jsonString, MyDataClass::class.java)

val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(MyDataClass::class.java)
val obj = jsonAdapter.fromJson(jsonString)

Gson and Moshi are libraries that help convert JSON text to Kotlin objects and back.

You need to create a data class that matches the JSON structure.

Examples
This example shows how to parse a simple JSON string into a User object using Gson.
Android Kotlin
data class User(val name: String, val age: Int)

val json = "{\"name\":\"Anna\", \"age\":25}"
val user = Gson().fromJson(json, User::class.java)
This example shows how to parse the same JSON string using Moshi.
Android Kotlin
data class User(val name: String, val age: Int)

val json = "{\"name\":\"Anna\", \"age\":25}"
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson(json)
Sample App

This program uses Gson to parse a JSON string into a Product object and prints its properties.

Android Kotlin
import com.google.gson.Gson

data class Product(val id: Int, val title: String)

fun main() {
  val json = "{\"id\":101, \"title\":\"Book\"}"
  val gson = Gson()
  val product = gson.fromJson(json, Product::class.java)
  println("Product id: ${product.id}, title: ${product.title}")
}
OutputSuccess
Important Notes

Make sure your data class properties exactly match the JSON keys.

If JSON keys differ, use @SerializedName (Gson) or @Json annotation (Moshi) to map them.

Always handle possible exceptions when parsing JSON to avoid app crashes.

Summary

JSON parsing converts text data into Kotlin objects for easy use.

Gson and Moshi are popular libraries for JSON parsing in Android.

Define data classes that match your JSON structure before parsing.