Moshi: A Modern JSON Library
Moshi is a modern JSON library for Android, Java, and Kotlin. It makes it easy to parse JSON into Java and Kotlin classes and serialize them back to JSON. It is designed to be fast, efficient, and highly customizable.
Built by Square, Moshi is a mature and robust library that leverages the high-performance I/O capabilities of Okio and is a perfect companion to OkHttp.
Key Features
- Simple & Clear API: Moshi's API is designed to be straightforward. Get a
JsonAdapter
for your type and you're ready to go. - First-Class Kotlin Support: Moshi understands Kotlin's non-nullable types and default parameter values. It offers both reflection-based and codegen-based adapters to suit your project's needs.
- Powerful Customization: Easily customize JSON conversion with
@ToJson
and@FromJson
methods, or build powerful, composableJsonAdapter.Factory
implementations for advanced use cases. - Robust Error Handling: Moshi provides clear
JsonDataException
errors when JSON data doesn't match your expected structure, making debugging easier. - Performance: Built on top of Okio, Moshi is designed for performance, minimizing memory allocations and I/O overhead.
- Annotation-Driven Configuration: Use annotations like
@Json
,@JsonClass
, and@JsonQualifier
to configure serialization and deserialization directly in your model classes.
A Quick Example
Moshi can easily parse a JSON string into your custom types.
Your JSON
{
"hidden_card": {
"rank": "6",
"suit": "SPADES"
},
"visible_cards": [
{
"rank": "4",
"suit": "CLUBS"
},
{
"rank": "A",
"suit": "HEARTS"
}
]
}
Your Kotlin Code
// Your data classes
class BlackjackHand(
val hidden_card: Card,
val visible_cards: List<Card>,
)
class Card(
val rank: Char,
val suit: Suit
)
enum class Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}
// Parsing the JSON
val json: String = "..." // Your JSON from above
val moshi: Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory()) // Add for Kotlin reflection support
.build()
val jsonAdapter: JsonAdapter<BlackjackHand> = moshi.adapter<BlackjackHand>()
val blackjackHand = jsonAdapter.fromJson(json)
println(blackjackHand)
And serializing an object back to JSON is just as simple:
val blackjackHand = BlackjackHand(
Card('6', Suit.SPADES),
listOf(Card('4', Suit.CLUBS), Card('A', Suit.HEARTS))
)
val json: String = jsonAdapter.toJson(blackjackHand)
println(json)
Ready to get started? Check out the Installation guide and the Quick Start tutorial.