Reputation: 1156
I am facing an error No JsonAdapter for R
when parsing JSON to data class inside a generic function, I researched and tried many ways but it is still not working.
The problem is that generic function
doesn't know what is actually the type of generic parameter R
so I can't manually assign the type of R when parsing.
How can I resolve this problem? :(
fun <T, R> sendRequest(msg: Deribit.Request.Message<T>): Deribit.Response.Result<R> {
...
val type = object : TypeToken<Deribit.Response.Result<R>>() {}.type
return moshi.adapter<Deribit.Response.Result<R>>(
type
).fromJson(jsonElement.toString())
...
}
I also use reified
function that return ParameterizedTypeReference
but it still not working
private inline fun <reified T: Any> typeRef(): ParameterizedTypeReference<T> = object: ParameterizedTypeReference<T>(){}
...
// USAGE
val data = moshi.adapter<Deribit.Response.Result<R>>(
typeRef<Deribit.Response.Result<R>>().type
).fromJson(jsonElement.toString())
Thank you and best regards!!!
Upvotes: 0
Views: 1166
Reputation: 170815
Making it
inline fun <reified T, reified R> sendRequest...
should work. Alternately, pass the type you need or enough to construct it as an argument. E.g.
fun <T, R> sendRequest(msg: Deribit.Request.Message<T>, clazzR: Class<R>): Deribit.Response.Result<R> {
// Type object for Result<R>
val type = Types.newParameterizedType(Deribit.Response.Result::class.java, clazzR)
...
}
Upvotes: 1