Moshi JSON to POJO: The Android Way
Square's modern JSON library for Android and Kotlin. Faster than Gson, safer for Kotlin, and built for Retrofit.
What is Moshi?
Moshi is a modern JSON library created by Square (the same team behind Retrofit, OkHttp, and Picasso). It's designed specifically for Kotlin and Android.
Faster
Compile-time adapters
Kotlin-Safe
Respects null safety
Retrofit Ready
Native integration
Basic Moshi Usage
@JsonClass(generateAdapter = true)
data class User(
@Json(name = "user_name") val name: String,
val age: Int,
val email: String? // nullable
)
// 2. Create Moshi instance
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// 3. Parse JSON
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson(jsonString)
Moshi vs Gson Comparison
| Feature | Moshi | Gson |
|---|---|---|
| Kotlin Null Safety | ✗ Unsafe | |
| Code Generation | ✗ Reflection only | |
| Retrofit Native | ||
| ProGuard/R8 | No rules needed | Needs keep rules |
| APK Size | ~120 KB | ~250 KB |
Moshi with Retrofit
Moshi integrates seamlessly with Retrofit for API calls:
implementation("com.squareup.moshi:moshi-kotlin:1.15.0")
implementation("com.squareup.retrofit2:converter-moshi:2.9.0")
kapt("com.squareup.moshi:moshi-kotlin-codegen:1.15.0")
// Create Retrofit with Moshi
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
Custom Type Adapters
Handle custom types like Date, BigDecimal, or enums with custom adapters:
class DateAdapter {
@ToJson
fun toJson(date: Date): String {
return SimpleDateFormat("yyyy-MM-dd").format(date)
}
@FromJson
fun fromJson(json: String): Date {
return SimpleDateFormat("yyyy-MM-dd").parse(json)!!
}
}
// Add to Moshi
val moshi = Moshi.Builder()
.add(DateAdapter())
.add(KotlinJsonAdapterFactory())
.build()
Common Questions
When to use @JsonClass?
Always use @JsonClass(generateAdapter = true) for compile-time code generation. It's faster and works with ProGuard without extra rules.
Moshi vs kotlinx.serialization?
Use Moshi for Android apps with Retrofit. Use kotlinx.serialization for Kotlin Multiplatform.
Generate Moshi-Ready Data Classes
Our converter outputs Kotlin data classes compatible with Moshi annotations.
Convert JSON to Kotlin