Moshi: Modern JSON for Kotlin & Android
Moshi is a modern JSON library that maps JSON strings to your Kotlin/Java objects. It's a translator between API text and your app's data classes, built with Kotlin-first features. The footgun: Kotlin classes require Moshi's codegen or reflection adapter.
WHY IT EXISTS Older JSON libraries were built for Java and rely heavily on reflection, which can be slow on Android and doesn't always handle Kotlin's features like non-nullability and default parameters gracefully. Moshi was created to be a modern, performance-focused library that treats Kotlin as a first-class citizen.
THE MENTAL MODEL Think of Moshi as a factory for expert data translators. For every data class (like User or Product), you request a specialized JsonAdapter. This adapter knows exactly how to read a JSON string to construct a User object (deserialization) and how to take a User object and write it as a JSON string (serialization).
HOW IT WORKS You create a central Moshi instance using Moshi.Builder(). To parse or serialize a specific class, you ask the Moshi instance for an adapter: moshi.adapter(MyClass.class). This adapter provides two main methods: fromJson() to parse a JSON string into an object, and toJson() to serialize an object into a string. For Kotlin, Moshi needs help to understand the language's features. You provide this help by either generating adapters at compile time with the moshi-kotlin-codegen library or by adding a runtime reflection adapter, KotlinJsonAdapterFactory.
WHEN TO USE IT Use Moshi in modern Android projects, especially those written primarily in Kotlin. It is the recommended JSON library for Retrofit (another Square library) for handling network API responses. Its performance shines when using kotlin-codegen, which avoids the speed and stability penalties of runtime reflection.
WHEN NOT TO USE IT For trivial, one-off JSON parsing, Android's built-in JSONObject might be simpler than adding a new dependency. If you're on a legacy Java project already standardized on another library like Gson or Jackson, migrating may not be worth the effort unless you face specific performance or Kotlin interoperability problems.
ONE CANONICAL EXAMPLE To parse a JSON string into a Kotlin data class, you first build a Moshi instance, then get the specific adapter for your data class, and finally call fromJson().
data class Player(val name: String, val score: Int)
val json = "{\"name\":\"Jesse\",\"score\":100}" val moshi = Moshi.Builder().build() val adapter = moshi.adapter(Player::class.java) val player = adapter.fromJson(json) // The player object is now: Player(name="Jesse", score=100)
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.