Kotlinで、Moshiを使う場合の方法を記載します。
app/build.gradle.kts
implementation("com.squareup.moshi:moshi-kotlin:1.12.0")
kapt(com.squareup.moshi:moshi-kotlin-codegen:1.12.0)
Adapterの登録を行います。
DaggerなどのDIで、Module化すると楽になります。
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
- Hiltを利用した場合
@Module
@InstallIn(SingletonComponent::class)
class JsonModule {
@Provides
@Singleton
fun provideMoshi(): Moshi {
return Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
}
}
Json定義
JavaのMoshiの場合、定義出来る型が決まっていました。
それ以外を使用する場合、自前でアダプターを用意する必要があります。
- Primitives (int, float, char...) and their boxed counterparts (Integer, Float, Character...).
- Arrays, Collections, Lists, Sets, and Maps
- Strings
- Enums
Kotlinの場合、Kotlinの型が使用できるため、Anyクラスなど使用することが可能です。
@JsonClass(generateAdapter = true)
data class Request(
val name: String,
val parameters: Any?
)
文字列からJSON
val text = "..."
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(Request::class.java)
val request = adapter.toJson(text)
JSONから文字列
val request = Request("name", 1)
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(Request::class.java)
val str = adapter.fromJson(request)
List型の場合
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
val type = Types.newParameterizedType(List::class.java, String::class.java)
val adapter = moshi.adapter(type)
moshi-kotlin-codegenは、簡単に使用できますので、是非お試しください。