LoginSignup
1
2

More than 5 years have passed since last update.

[kotlin]Retrofit2のリクエストボディにキャメルケースのkeyを入れたい(2018/9/2追記)

Last updated at Posted at 2018-08-23

Retrofit2でpostしようとした時にリクエストボディにクラスを入れたらキャメルケースの変数がスネークケースのkeyとして変換されてしまう。

RetrofitInterface.kt
interface RetrofitInterface {

    @POST("/api/sample")
    fun postSample(@Body body: RequestModel): Call<ResponseModel>
}
model.kt

class RequestModel(loginId: String,
            password: String) {

    val loginId = loginId
    val password = password
}

結果

{
    "login_id":"aaa",
    "password":"bbb"
}

サーバー側がキャメルケースで設計してしまってる場合、これはまずい。

BodyにMapを挿入する

クラスではなくてMapでbodyを指定すると無事キャメルケースになる。

RetrofitInterface.kt
interface RetrofitInterface {

    @POST("/api/sample")
    fun postSample(@Body body: Map<String, String>): Call<ResponseModel>
}
val body = mapOf("loginId" to "aaa", "password" to "bbb")

結果

{
    "loginId":"aaa",
    "password":"bbb"
}

gsonのFieldNamingPolicyを設定する

(2018/09/02追記)FieldNamingPolicyに依存されるということを存じ上げなかった。

参考: https://qiita.com/yysk/items/e549ba40bc2accfdff35

今回は叩くAPIのレスポンスがキャメルケースとスネークケースと混在していたので、IDENTITYを設定して解決


val gson: Gson = GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .create()


val restAdapter = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient)
                .baseUrl("https://xxxx.jp")
                .build()
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2