Does anybody here use KotlinxSerialization with Retrofit?
c
Does anybody here use KotlinxSerialization with Retrofit?
w
We use it, and works fine, at least for our use. We don’t have any custom serialisation, we just have classes annotated with
@Serializable
and properties annotated with
@SerialName
. So far so good.
c
May I also ask @wbertan what REST APIs do you call? Like GET, POST etc? Also I was wondering about this issue. Since there is no convertor yet by square. Although I know Jake Wharton is the same person, still. https://github.com/JakeWharton/retrofit2-kotlinx-serialization-converter/issues/39
w
Thanks, wasn’t aware of that issue. We use
GET
and
PATCH
also having a
Path
, but we use simple
String
as a parameter, so we don’t have that issue. For us here is fine, as it seems simple enough and on our architecture APIs are only used in Repository classes, so we didn’t feel the need to make it strict in the parameters to be a class type too.
c
Have you tried others though before? Moshi or Jackson or something else?
w
In another project we use GSON, we avoided as the issue in not being Kotlin friendly and we want some default values for nullable fields. I think we discussed Moshi, etc. but KotlinxSerialization was preferable just because seems simple, Kotlin friendly and get the job done, and it was new (and we were using a lot of new libs and trying new things in the new project). But no particular reason to reject Moshi and others either.
c
My main issue is ability to parse nulls to default values. Have been using Moshi all along for now. Would you be able to send me your JSON Configuration for Kotlinx?
I was looking on how to set it up, came across this but it does not seem to work
Copy code
private val contentType =  "application/json".toMediaType()
    private val jsonConfig = JsonConfiguration.Stable.copy(prettyPrint = true, ignoreUnknownKeys = true)
    private val json = Json(jsonConfig)
    private val userApi = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(json.asConverterFactory(contentType))
        .build()
        .create(UserApi::class.java)
w
🤔 To be honest we don’t have many use of parsing nulls to default values, but a few we have seems to work. To be clear we usually set default values in the mapping from DTO to Data, that is our reason, we want the DTO to be as much as the same from what we really get from the API. We configure it as this:
Copy code
val contentType = "application/json".toMediaType()
            val jsonConverter = Json {
                ignoreUnknownKeys = true
            }.asConverterFactory(contentType)

            return Retrofit.Builder()
                .baseUrl(urlProvider.url)
                .addConverterFactory(jsonConverter)
And an example of a DTO with default value:
Copy code
@Serializable
data class SomeDto(
    @SerialName("fieldName") val fieldName: Boolean? = false
)
1132 Views