Core Annotations
Moshi uses a set of annotations to configure how your data classes are serialized and deserialized. Here are the most important ones.
@JsonClass
This annotation is key for enabling Kotlin code generation.
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Player(val name: String)
generateAdapter
: A boolean that, whentrue
, tells the Moshi KSP processor to generate aJsonAdapter
for this class at compile time. This is the primary way to enable high-performance serialization for Kotlin classes.generator
: An optional string used by third-party code generation libraries. If you are using Moshi's standard codegen, you should leave this empty.
@Json
This annotation customizes how a specific field or property is handled.
name
Use name
to map a property to a different key in the JSON. This is essential when the JSON key contains characters that are not valid in a Kotlin property name, or if you want to follow different naming conventions.
@JsonClass(generateAdapter = true)
data class Player(
val username: String,
@Json(name = "lucky number") val luckyNumber: Int
)
// Corresponds to JSON: {"username":"jesse","lucky number":32}
ignore
Use ignore = true
to completely exclude a property from serialization and deserialization. The property will not be written to JSON, and its value will be ignored if present in the incoming JSON. Ignored properties in a primary constructor must have a default value.
@JsonClass(generateAdapter = true)
data class User(
val id: Long,
val email: String,
@Json(ignore = true) var sessionToken: String? = null
)
// JSON: {"id":123,"email":"user@example.com"}
Using the transient
keyword on a property has the same effect as @Json(ignore = true)
.
@ToJson
and @FromJson
These method annotations are used to create custom adapters. They tell Moshi how to convert a type to and from JSON.
- A method annotated with
@ToJson
converts an instance of your custom type into a JSON-compatible type (like aString
,Map
, or another class). - A method annotated with
@FromJson
performs the reverse conversion.
See the Custom Adapters guide for a detailed explanation.
@JsonQualifier
This is a meta-annotation used to create your own annotations. These custom annotations allow you to define different JSON representations for the same data type.
For example, you could have one adapter for an Int
that serializes it as a number, and another adapter qualified with @HexColor
that serializes it as a hex color string like "#ff0000"
.
See the Qualifiers guide for an in-depth look.