Kotlin support for Moshi JSON library using reflection, providing KotlinJsonAdapterFactory for seamless JSON serialization/deserialization of Kotlin data classes.
npx @tessl/cli install tessl/maven-com-squareup-moshi--moshi-kotlin@1.15.0Moshi Kotlin provides Kotlin-specific support for the Moshi JSON library through reflection-based JSON adapters. It enables seamless serialization and deserialization of Kotlin data classes with proper support for Kotlin language features like non-nullable types, default parameter values, and value classes.
implementation "com.squareup.moshi:moshi-kotlin:1.15.2"<dependency><groupId>com.squareup.moshi</groupId><artifactId>moshi-kotlin</artifactId><version>1.15.2</version></dependency>import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.JsonAdapterimport com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
// Create Moshi instance with Kotlin support
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// Define a Kotlin data class
data class User(
val name: String,
val age: Int,
val isActive: Boolean = true // Default parameter value
)
// Create adapter for the data class
val adapter: JsonAdapter<User> = moshi.adapter(User::class.java)
// Serialize to JSON
val user = User("Alice", 25)
val json: String = adapter.toJson(user)
// Result: {"name":"Alice","age":25,"isActive":true}
// Deserialize from JSON
val userFromJson: User? = adapter.fromJson(json)The primary API that enables Kotlin-specific JSON serialization and deserialization for Moshi.
class KotlinJsonAdapterFactory : JsonAdapter.Factory {
override fun create(
type: Type,
annotations: MutableSet<out Annotation>,
moshi: Moshi
): JsonAdapter<*>?
}Parameters:
type: Type - The type for which to create a JSON adapterannotations: MutableSet<out Annotation> - Annotations present on the field or methodmoshi: Moshi - The Moshi instance to use for creating nested adaptersReturns:
JsonAdapter<*>? - A JSON adapter for the given type wrapped with nullSafe(), or null if this factory cannot create one for the specified typeKey Features:
var) and immutable (val) properties@Json annotations for custom field names@JsonClass(generateAdapter = true)) when available, falls back to reflection-based adaptersnullSafe() for proper null handlingSupported Class Types:
Unsupported Class Types:
Usage Example:
// Basic data class
data class Person(val name: String, val age: Int)
// Data class with default values
data class Account(
val id: String,
val balance: Double = 0.0,
val isActive: Boolean = true
)
// Data class with @Json annotation
data class ApiResponse(
@Json(name = "user_id") val userId: String,
@Json(name = "full_name") val fullName: String
)
// Using the factory
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val personAdapter = moshi.adapter(Person::class.java)
val accountAdapter = moshi.adapter(Account::class.java)
val responseAdapter = moshi.adapter(ApiResponse::class.java)For backward compatibility, there's a deprecated factory in the original package:
@Deprecated(
message = "this moved to avoid a package name conflict in the Java Platform Module System.",
replaceWith = ReplaceWith("com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory")
)
class KotlinJsonAdapterFactory : JsonAdapter.FactoryLocation: com.squareup.moshi.KotlinJsonAdapterFactory
Status: Deprecated - use com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory instead
The KotlinJsonAdapterFactory and generated adapters can throw several types of exceptions:
JsonDataException: Thrown when JSON data doesn't match expected Kotlin types
unexpectedNull() utilitymissingProperty() utilityIllegalArgumentException: Thrown for unsupported class types (via require() statements in the factory)
Usage Example:
try {
val user = adapter.fromJson("""{"name":null,"age":25}""")
} catch (e: JsonDataException) {
// Handle null value for non-nullable property
println("JSON data error: ${e.message}")
}import com.squareup.moshi.Json
data class User(
@Json(name = "full_name") val fullName: String,
@Json(name = "user_age") val age: Int
)data class User(
val name: String,
val age: Int,
@Transient val tempData: String = "default" // Excluded from JSON
)data class User(
val name: String, // Constructor parameter
val age: Int // Constructor parameter
) {
var lastLogin: Long = 0 // Additional property, not in constructor
}val moshi = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter()) // Custom adapters first
.addLast(KotlinJsonAdapterFactory()) // Use addLast() for general-purpose adapters
.build()Note: Use addLast() when registering KotlinJsonAdapterFactory to ensure custom adapters take precedence over the reflection-based factory.
This package has the following dependencies:
Required Dependencies:
com.squareup.moshi:moshi - Core Moshi library (automatically included as API dependency)org.jetbrains.kotlin:kotlin-reflect - Kotlin reflection library (automatically included as API dependency)Runtime Requirements:
kotlin-stdlib) must be present on the classpath during compilation for proper metadata annotationsNotes:
kotlin-reflect dependency adds approximately 2.5 MiB to your applicationmoshi-kotlin-codegen instead for compile-time generationAll types are provided by the Moshi core library. The KotlinJsonAdapterFactory uses reflection to work with Kotlin's type system and doesn't define additional types beyond the factory class itself.