Search code examples
androidkotlinretrofit2

How to use model in query string for Retrofit 2?


I am using a class model like below to hold the search data information,

data class SearchDataModel (
    var keyword: String? = "",
    var from: String? = "",
    var to: String? = "",
    var page: Int? = null,
    var sortby: String? = null,
    var orderby: String? = null,
    var itemsperpage: Int? = null
)

For posting data we can use the call,

@POST("/data/save")
fun saveData(@Body postData: PostDataModel)

How to achieve the same for query string something like the one below?

@GET("/data/search")
fun searchData(@QueryString searchData: SearchDataModel)

I'm trying to prevent having lots of parameter in the function and have an optional query string parameter.


Solution

  • You should use URL encoding and pass Map into query.

    @FormUrlEncoded
    @GET("/data/search")
    fun searchData(@FieldMap searchData: Map<String, String>)
    

    Then have a method in your SearchDataModel to add properties to the Map<String, String> and pass it to searchData function.

    data class SearchDataModel (
        var keyword: String? = "",
        var from: String? = "",
        var to: String? = "",
        var page: Int? = null,
        var sortby: String? = null,
        var orderby: String? = null,
        var itemsperpage: Int? = null
    
        fun toMap(): Map<String, String> {
            return mapOf(
                "keyword" to keyword,
                "from" to from,
                "to" to to,
                "page" to page,
                "sortby" to sortby,
                "orderby" to orderby,
                "itemsperpage" to itemsperpage
            )
        }
    )
    

    Use it like that: searchData(searchData: yourData.toMap())


    Good luck :)