cbeust / klaxon

A JSON parser for Kotlin
Apache License 2.0
1.85k stars 123 forks source link

Add Retrofit converter #101

Open tgirard12 opened 6 years ago

tgirard12 commented 6 years ago

It will be nice to provide a simple way to use klaxon and retrofit : https://github.com/square/retrofit/tree/master/retrofit-converters

Thanks

meSmashsta commented 3 years ago

Hello, any updates? :o

marlonlom commented 1 year ago

Hello @meSmashsta @tgirard12

Reading the issue, i started to check it and try to make something understandeable, think of it as creating a custom converter for retrofit2.

When creating a custom Converter<ResponseBody, T>, i found that, when using the function Klaxon().parse<T>(...) it appear to happen the following error:

Cannot use 'T' as reified type parameter. Use a class instead.

Sample code for response body converter:

import com.beust.klaxon.Klaxon
import okhttp3.ResponseBody
import retrofit2.Converter

class KlaxonResponseBodyConverter<T> constructor(
  private val klaxon: Klaxon
) : Converter<ResponseBody, T> {

  override fun convert(value: ResponseBody): T? {
    var response: T? = null
    response = klaxon.parse<T>(value.byteStream()) // Cannot use 'T' as reified type parameter. Use a class instead.
    return response
  }

}

The sample code and the found error are related to issue #104

I think this is not an issue, but a feature for Retrofit2-converters to be added in the future. the problem is that while using java, i dont think they accept to add a kotlin-first utility inside a java library.

So, the next step could be creating a pull request in retrofit2 repository for this, and, in a community/friendly way, try to accomplish this as a community made library.