JSON Parsing
Kotlin
Kotlin Programming
JSON in Kotlin
Android Development

How to parse JSON in Kotlin?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Parsing JSON in Kotlin is a common task when working with modern web and mobile applications. Kotlin provides several libraries to parse JSON data, such as Gson, Moshi, and kotlinx.serialization. Each library has its own characteristics and use cases, and in this article, we'll explore how to use these libraries to parse JSON efficiently in Kotlin.

JSON Parsing Libraries in Kotlin

1. Gson

Gson is a popular Java library developed by Google that can be used to convert Kotlin (and Java) objects into their JSON representation and vice versa. Despite being a Java library, Gson is robust and works seamlessly with Kotlin.

Example with Gson

kotlin
1// Add dependency in your build.gradle.kts
2dependencies {
3    implementation("com.google.code.gson:gson:2.8.8")
4}
5
6import com.google.gson.Gson
7
8data class User(val name: String, val age: Int)
9
10fun main() {
11    val json = """{"name": "John Doe", "age": 30}"""
12    val gson = Gson()
13    
14    // Parse JSON to Kotlin object
15    val user: User = gson.fromJson(json, User::class.java)
16    println("User Name: ${user.name}, User Age: ${user.age}")
17    
18    // Convert Kotlin object to JSON
19    val userJson = gson.toJson(user)
20    println("JSON Representation: $userJson")
21}

2. Moshi

Moshi is a modern JSON library for Android and Java by Square. It takes advantage of Kotlin's language features and provides first-class support for Kotlin.

Example with Moshi

kotlin
1// Add dependency in your build.gradle.kts
2dependencies {
3    implementation("com.squareup.moshi:moshi:1.12.0")
4    implementation("com.squareup.moshi:moshi-kotlin:1.12.0")
5}
6
7import com.squareup.moshi.Moshi
8import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
9
10data class User(val name: String, val age: Int)
11
12fun main() {
13    val json = """{"name": "Jane Doe", "age": 25}"""
14    val moshi = Moshi.Builder()
15        .add(KotlinJsonAdapterFactory())
16        .build()
17    
18    val jsonAdapter = moshi.adapter(User::class.java)
19    
20    // Parse JSON to Kotlin object
21    val user: User? = jsonAdapter.fromJson(json)
22    println("User Name: ${user?.name}, User Age: ${user?.age}")
23    
24    // Convert Kotlin object to JSON
25    val userJson = jsonAdapter.toJson(user)
26    println("JSON Representation: $userJson")
27}

3. kotlinx.serialization

Kotlinx.serialization is Kotlin-specific and developed under the Kotlin umbrella. It provides an idiomatic and modern API for both serialization and deserialization and supports various formats including JSON, CBOR, Protobuf, and more.

Example with kotlinx.serialization

kotlin
1// Add dependency in your build.gradle.kts
2dependencies {
3    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0")
4}
5
6import kotlinx.serialization.*
7import kotlinx.serialization.json.*
8
9@Serializable
10data class User(val name: String, val age: Int)
11
12fun main() {
13    val json = """{"name": "Alice Doe", "age": 28}"""
14    
15    // Parse JSON to Kotlin object
16    val user = Json.decodeFromString<User>(json)
17    println("User Name: ${user.name}, User Age: ${user.age}")
18    
19    // Convert Kotlin object to JSON
20    val userJson = Json.encodeToString(user)
21    println("JSON Representation: $userJson")
22}

Key Points Comparison Table

LibraryLanguage SupportMapping CustomizationKotlin SupportDependencies
GsonJava, KotlinAnnotationsPartial (requires annotations) No null safety by defaultgson:2.8.8
MoshiJava, KotlinAdaptersFull (ideal for Kotlin) Provides null safetymoshi:1.12.0 moshi-kotlin:1.12.0
kotlinx.serializationKotlinPluginsNative Kotlin support Null safety Compile-time checkskotlinx-serialization-json:1.3.0

Additional Subtopics

Error Handling

When parsing JSON, it's crucial to handle potential errors gracefully. All the libraries mentioned allow for error handling through exceptions. For instance, Gson and Moshi throw parse exceptions when things go awry, while kotlinx.serialization will throw SerializationException.

It's important to catch and manage these exceptions to avoid application crashes, especially when dealing with user-generated JSON input or dynamic content from web servers.

Performance Considerations

Performance-wise, each library has its merits. Gson is slightly slower compared to others due to reflection; however, it's battle-tested and provides a wide array of customization. Moshi improves upon Gson’s performance with better reflection avoidance. Kotlinx.serialization relies on Kotlin's compiler, offering optimal performance and tight integration into the Kotlin ecosystem.

Custom Annotations and Adapters

For more complex JSON structures, custom annotations (as provided in Gson and Moshi) or plugins (in kotlinx.serialization) might be necessary. Gson and Moshi use reflections for custom types, whereas kotlinx.serialization uses compiler plugins for compile-time safety.

In conclusion, choosing the right library depends on your specific application needs, preferred language features, and performance requirements. Each library has its strengths and trade-offs suitable for different scenarios.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.