Running into a slight issue with Retrofit2 and ser...
# squarelibraries
m
Running into a slight issue with Retrofit2 and serialization of custom types. This is how I'm creating my Retrofit instance:
Copy code
this.rfBuilder.apply {
            baseUrl(BASE_URL)
            addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().apply {
                        registerTypeAdapter(SearchQuery::class.java, SearchQueryAdapter())
                        excludeFieldsWithoutExposeAnnotation()
                        setPrettyPrinting()
                    }.create()
                )
            )
            client(
                OkHttpClient.Builder().apply {
                    addInterceptor { chain ->
                        val original = chain.request()

                        val requestBuilder = original.newBuilder().addHeader("User-Agent", USER_AGENT)
                        val request = requestBuilder.build()
                        chain.proceed(request)
                    }
                }.build()
            )
        }
I've created a SearchQueryAdapter that implements
JsonSerializer
and the
serialize
function. This is my function declaration in my Retrofit service:
Copy code
@GET("posts")
    fun searchListings(
        @Query("request") searchQuery: SearchQuery,
        @Query("count") count: Int = 50,
        @Query("max_id") maxId: Int = 1
    ): Call<GetListingsResponse>
What's happening is that the query parameter for searchQuery doesn't serialize in that the value of the parameter becomes
SearchQuery( <serialized content here>)
, which isn't valid for the API. What am I doing wrong here?
g
Retrofit doesn’t apply converter to query params You have a few options 1. convert SearchQuery to required query string manually before passing it to retrofit 2. Override toString() for SearchQuery to return required value 3. Use @QueryMap that encapsulate this behavior under the hood (but probably it a bit overkill for your case)
m
Ahhhh
Okay, that would explain everything then. Thank you so much Andrey!