or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-com-squareup-moshi--moshi-kotlin

Kotlin support for Moshi JSON library using reflection, providing KotlinJsonAdapterFactory for seamless JSON serialization/deserialization of Kotlin data classes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.moshi/moshi-kotlin@1.15.x

To install, run

npx @tessl/cli install tessl/maven-com-squareup-moshi--moshi-kotlin@1.15.0

index.mddocs/

Moshi Kotlin

Moshi 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.

Package Information

  • Package Name: moshi-kotlin
  • Package Type: maven
  • Group ID: com.squareup.moshi
  • Artifact ID: moshi-kotlin
  • Language: Kotlin
  • Installation:
    • Gradle: implementation "com.squareup.moshi:moshi-kotlin:1.15.2"
    • Maven: <dependency><groupId>com.squareup.moshi</groupId><artifactId>moshi-kotlin</artifactId><version>1.15.2</version></dependency>

Core Imports

import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.JsonAdapter

Basic Usage

import 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)

Capabilities

Kotlin JSON Adapter Factory

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 adapter
  • annotations: MutableSet<out Annotation> - Annotations present on the field or method
  • moshi: Moshi - The Moshi instance to use for creating nested adapters

Returns:

  • JsonAdapter<*>? - A JSON adapter for the given type wrapped with nullSafe(), or null if this factory cannot create one for the specified type

Key Features:

  • Kotlin Data Classes: Automatically handles data classes with primary constructors
  • Nullable Types: Respects Kotlin's nullable and non-nullable type system
  • Default Parameters: Supports constructor parameters with default values
  • Property Binding: Handles both mutable (var) and immutable (val) properties
  • Annotation Support: Works with @Json annotations for custom field names
  • Value Classes: Supports Kotlin value classes with proper type resolution
  • Generated Adapter Precedence: Automatically prefers generated adapters (created with @JsonClass(generateAdapter = true)) when available, falls back to reflection-based adapters
  • Null Safety: All returned adapters are automatically wrapped with nullSafe() for proper null handling

Supported Class Types:

  • Data classes
  • Regular classes with primary constructors
  • Classes with both constructor parameters and additional properties
  • Classes with optional/default constructor parameters

Unsupported Class Types:

  • Interfaces
  • Enums (use standard Moshi enum support)
  • Abstract classes
  • Inner classes
  • Local classes
  • Object declarations
  • Sealed classes (requires custom adapters)

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)

Deprecated API (Compatibility)

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.Factory

Location: com.squareup.moshi.KotlinJsonAdapterFactory
Status: Deprecated - use com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory instead

Error Handling

The KotlinJsonAdapterFactory and generated adapters can throw several types of exceptions:

JsonDataException: Thrown when JSON data doesn't match expected Kotlin types

  • Multiple values for the same property: "Multiple values for '${propertyName}' at ${reader.path}"
  • Null values for non-nullable properties: Wrapped with unexpectedNull() utility
  • Missing values for required constructor parameters: Wrapped with missingProperty() utility

IllegalArgumentException: Thrown for unsupported class types (via require() statements in the factory)

  • Local classes: "Cannot serialize local class or object expression ${className}"
  • Inner classes: "Cannot serialize inner class ${className}"
  • Abstract classes: "Cannot serialize abstract class ${className}"
  • Object declarations: "Cannot serialize object declaration ${className}"
  • Sealed classes: "Cannot reflectively serialize sealed class ${className}. Please register an adapter."

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}")
}

Advanced Usage

Custom Field Names with @Json

import com.squareup.moshi.Json

data class User(
    @Json(name = "full_name") val fullName: String,
    @Json(name = "user_age") val age: Int
)

Transient Fields

data class User(
    val name: String,
    val age: Int,
    @Transient val tempData: String = "default"  // Excluded from JSON
)

Mixed Constructor and Property Binding

data class User(
    val name: String,  // Constructor parameter
    val age: Int       // Constructor parameter
) {
    var lastLogin: Long = 0  // Additional property, not in constructor
}

Integration with Moshi Adapters

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.

Dependencies

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 Standard Library (kotlin-stdlib) must be present on the classpath during compilation for proper metadata annotations
  • Minimum supported versions align with the core Moshi library requirements

Notes:

  • The kotlin-reflect dependency adds approximately 2.5 MiB to your application
  • For applications where this size is prohibitive, consider using moshi-kotlin-codegen instead for compile-time generation
  • When both reflection and codegen adapters are present, generated adapters take precedence

Types

All 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.