![](/img/trans.png)
[英]How to get the request url while using moshi 'deferred' with retrofit 2.0
[英]How to specify a different name for json key while using Retrofit + Moshi
我需要使用以下 json 向我的后端發出 POST 請求:
{
start_time: 123456789
}
我在 Retrofit 請求中為正文創建了以下數據 class:
data class MyRequestBody(
@Json(name="start_time")
val startTime: Long
)
但是當我檢查我的后端時,請求包含startTime
字段而不是start_time
。 如何為 json 序列化更改此變量的名稱?
編輯:我的 build.gradle:
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
我的 api 接口:
internal interface RemoteTopicApi {
@POST("xyz/")
suspend fun getData(@Body body: MyRequestBody)
}
Retrofit 生成器:
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
1-添加那些 moshi 依賴項:
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
// Moshi
implementation 'com.squareup.moshi:moshi-kotlin:1.13.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.13.0'
2-將 Retrofit Builder 更改為:
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(
Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
))
.build()
這解決了我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.