我正在使用如下所示的类模型来保存搜索数据信息,
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
)
要发布数据,我们可以使用呼叫
@POST("/data/save")
fun saveData(@Body postData: PostDataModel)
如何对查询字符串实现相同的功能?
@GET("/data/search")
fun searchData(@QueryString searchData: SearchDataModel)
我正试图防止函数中包含很多参数,并避免使用可选的查询字符串参数。
答案 0 :(得分:1)
您应该使用URL编码,并将Map传递给查询。
@FormUrlEncoded
@GET("/data/search")
fun searchData(@FieldMap searchData: Map<String, String>)
然后在您的SearchDataModel
中有一个方法可以将属性添加到Map<String, String>
并将其传递给searchData
函数。
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
)
}
)
像这样使用它:searchData(searchData: yourData.toMap())