althaf
12/14/2023, 8:23 AM*inline fun* <*reified* T> Any.toCoCJson() {
*val* moshi: Moshi = Moshi.Builder().build()
*val* jsonAdapter: JsonAdapter<T> = moshi.adapter<T>()
*val* json: String = jsonAdapter.toJson(*this as* T)
}
Sam
12/14/2023, 8:36 AMType
or a Java Class
. Given a reified Kotlin type, you can get its corresponding Java class with T::class.java
, or you can get the Java Type
with typeOf<T>().javaType
. Of those two options, the second one is probably better, as it should be able to preserve more information about the type. So:
val jsonAdapter = moshi.adapter(typeOf<T>().javaType)
Sam
12/14/2023, 8:38 AMAny
and then cast it to T
?althaf
12/14/2023, 8:38 AM*return* jsonAdapter.toJson(*this*)
This was giving a compiler error
althaf
12/14/2023, 8:39 AMalthaf
12/14/2023, 8:39 AMSam
12/14/2023, 8:40 AMT
instead of Any
, unless there's a reason you can't use that approach.
inline fun <reified T> T.toCoCJson() { ... }
althaf
12/14/2023, 8:41 AMalthaf
12/14/2023, 8:41 AMSam
12/14/2023, 8:42 AM