Quick Start: Your First JSON Serialization
This guide will walk you through the basics of parsing a JSON string into a Kotlin object and serializing that object back into JSON.
1. Define Your Data Class
Let's start with a simple Kotlin data class to represent a player.
data class Player(
val username: String,
@Json(name = "lucky number") val luckyNumber: Int,
val roles: List<String>
)
Notice the @Json(name = ...)
annotation. This tells Moshi to map the luckyNumber
property to the "lucky number"
key in the JSON, which is useful when JSON keys are not valid Kotlin property names.
2. Create a Moshi Instance
To use Moshi, you need a Moshi
instance. Create one using its builder. For Kotlin classes, you'll also want to add the KotlinJsonAdapterFactory
.
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
val moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory()) // Enable Kotlin reflection
.build()
3. Parse JSON from a String
Now, let's take a JSON string and parse it into our Player
object.
First, get a JsonAdapter
for your Player
type from the Moshi
instance.
import com.squareup.moshi.JsonAdapter
// The adapter is cached, so it's efficient to request it multiple times.
val jsonAdapter: JsonAdapter<Player> = moshi.adapter(Player::class.java)
val json = """{
"username": "jesse",
"lucky number": 32,
"roles": ["admin", "user"]
}"""
val player = jsonAdapter.fromJson(json)
println(player)
// Output: Player(username=jesse, luckyNumber=32, roles=[admin, user])
Moshi handles parsing the string, mapping the JSON keys to the correct properties, and constructing the Player
instance with the data.
4. Serialize an Object to JSON
Going the other way is just as simple. Use the same JsonAdapter
to convert a Player
instance into a JSON string.
val newPlayer = Player("jake", 99, listOf("moderator"))
val jsonString: String = jsonAdapter.toJson(newPlayer)
println(jsonString)
// Output: {"username":"jake","lucky number":99,"roles":["moderator"]}
For a more readable, indented output, you can use the indent()
method on the adapter:
val prettyJsonString: String = jsonAdapter.indent(" ").toJson(newPlayer)
println(prettyJsonString)
// Output:
// {
// "username": "jake",
// "lucky number": 99,
// "roles": [
// "moderator"
// ]
// }
That's it! You've successfully used Moshi to serialize and deserialize a custom Kotlin type. Explore the rest of the documentation to learn about custom adapters, handling nulls, Kotlin code generation, and more.