Use @JsonQualifier to apply a specific type adapter to certain fields of a type without changing the encoding for all instances of that type. This is useful when the same type (e.g., Int) needs different JSON representations (e.g., a decimal number vs. a hex color string).
1. Define the qualifier:
@Retention(RUNTIME)
@JsonQualifier
annotation class HexColor
2. Apply to the field:
class Rectangle(
val width: Int,
val height: Int,
@HexColor val color: Int
)
3. Create the adapter using the qualifier:
class ColorAdapter {
@ToJson fun toJson(@HexColor rgb: Int): String {
return "#%06x".format(rgb)
}
@FromJson @HexColor fun fromJson(rgb: String): Int {
return rgb.substring(1).toInt(16)
}
}
4. Register the adapter:
val moshi = Moshi.Builder()
.add(ColorAdapter())
.build()
@Retention(RUNTIME)
@JsonQualifier
annotation class HexColor
class Rectangle(
val width: Int,
val height: Int,
@HexColor val color: Int
)
class ColorAdapter {
@ToJson fun toJson(@HexColor rgb: Int): String {
return "#%06x".format(rgb)
}
@FromJson @HexColor fun fromJson(rgb: String): Int {
return rgb.substring(1).toInt(16)
}
}