Skip to content
DeveloperMemos

A Quick Moshi Tutorial

Android, Moshi, JSON2 min read

Moshi is a powerful JSON library for Kotlin, developed by Square. It provides a simple and efficient way to parse and serialize JSON data in Android applications. Moshi integrates seamlessly with Kotlin and offers features such as type-safe parsing, data class support, and flexible JSON customization.

This tutorial will guide you through the process of setting up Moshi in your Android project and demonstrate some common usage scenarios with examples in Kotlin.

Adding Moshi to your Android Project

To use Moshi in your Android project, you need to add the necessary dependencies to your app-level build.gradle file. Open the build.gradle file and add the following lines:

1dependencies {
2 implementation "com.squareup.moshi:moshi:1.14.0"
3 kapt "com.squareup.moshi:moshi-kotlin-codegen:1.14.0"
4}

Once you've added the dependencies, sync your project to make the libraries available in your app.

Parsing JSON with Moshi

Moshi provides a convenient way to parse JSON data into Kotlin objects using its Moshi class. Let's say we have the following JSON data representing a user:

1{
2 "name": "John Doe",
3 "age": 30,
4 "email": "johndoe@example.com"
5}

To parse this JSON into a Kotlin object, we need to define a data class that represents the structure of the JSON:

1data class User(
2 val name: String,
3 val age: Int,
4 val email: String
5)

Now, let's see how we can parse the JSON using Moshi:

1val json = """{
2 "name": "John Doe",
3 "age": 30,
4 "email": "johndoe@example.com"
5}"""
6
7val moshi = Moshi.Builder().build()
8val adapter: JsonAdapter<User> = moshi.adapter(User::class.java)
9val user: User? = adapter.fromJson(json)
10
11if (user != null) {
12 // Parsing succeeded
13 // Use the user object here
14} else {
15 // Parsing failed
16 // Handle the error
17}

In the example above, we first create an instance of Moshi using its Builder class. Then, we create a JsonAdapter for the User class using the adapter() method. Finally, we use the fromJson() method to parse the JSON string into a User object. If the parsing succeeds, we can use the user object to access the parsed data.

Serializing Objects to JSON

Moshi also makes it easy to serialize Kotlin objects to JSON strings. Let's assume we have a User object and we want to convert it to JSON:

1val user = User("John Doe", 30, "johndoe@example.com")
2
3val moshi = Moshi.Builder().build()
4val adapter: JsonAdapter<User> = moshi.adapter(User::class.java)
5val json: String? = adapter.toJson(user)
6
7if (json != null) {
8 // Serialization succeeded
9 // Use the JSON string here
10} else {
11 // Serialization failed
12 // Handle
13
14 the error
15}

In the code snippet above, we create an instance of Moshi and a JsonAdapter for the User class as before. Then, we use the toJson() method to serialize the user object into a JSON string. If the serialization succeeds, we can use the json string to send or store the JSON data.

Customizing JSON Serialization and Deserialization

Moshi allows customization of the JSON serialization and deserialization process. You can annotate your data classes or provide custom adapters to handle specific JSON formats or transformations. This flexibility makes Moshi suitable for a wide range of JSON handling scenarios.

For example, let's say we have a data class Event representing an event with a date:

1data class Event(
2 val name: String,
3 @Json(name = "event_date") val date: Date
4)

In this case, we use the @Json annotation to specify a custom name for the date field in the JSON. Moshi will use this annotation during serialization and deserialization to match the field names correctly.

Wrap Up

Moshi is a versatile JSON library for Kotlin that provides powerful JSON parsing and serialization capabilities. In this tutorial, we learned how to set up Moshi in an Android project and explored its usage for parsing JSON into Kotlin objects and serializing objects to JSON. We also discovered how to customize the serialization and deserialization process with annotations and custom adapters. Now that you have a basic understanding of Moshi, you can leverage its features to handle JSON data efficiently in your Android applications!