您好我正在使用gson
库来映射对模型的响应值。我这样做,但它没有映射响应模型的值。我得到了50个模型的列表,但其中的值为零。
@Provides
@Singleton
fun provideRestApiHelper(
okHttpClient: OkHttpClient,
gson: Gson,
rxJava2CallAdapterFactory: RxJava2CallAdapterFactory): RestApi {
val builder = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.addConverterFactory(GsonConverterFactory.create(gson))
val retrofit = builder.client(okHttpClient).build()
return retrofit.create(RestApi::class.java)
}
RestApi.kt
interface RestApi {
@GET(ApiEndPoint.ENDPOINT_GITHUB_JOBS)
fun getJobsApiCall(): Observable<List<JobsResponse>>
}
ApiHelperImpl.kt
class ApiHelperImpl @Inject constructor(private val restApi: RestApi) : ApiHelper {
override fun getJobsApiCall(): Observable<List<JobsResponse>> {
return restApi.getJobsApiCall()
}
}
JobsResponse.kt
data class JobsResponse(
@field:SerializedName("company_logo")
val companyLogo: String?,
@field:SerializedName("how_to_apply")
val howToApply: String?,
@field:SerializedName("created_at")
val createdAt: String?,
@field:SerializedName("description")
val description: String?,
@field:SerializedName("location")
val location: String?,
@field:SerializedName("company")
val company: String?,
@field:SerializedName("company_url")
val companyUrl: String?,
@field:SerializedName("id")
val id: String?,
@field:SerializedName("title")
val title: String?,
@field:SerializedName("type")
val type: String?,
@field:SerializedName("url")
val url: String?
) : BaseResponse()
我正在调用此API https://jobs.github.com/positions.json。有谁知道可能是什么问题?
答案 0 :(得分:1)
那是因为你依赖于自动转换的java代码
删除@field:SerializedName
将其更改为@SerializedName
不要将它们放入primary constructor
像这样定义它们:
data class JobsResponse(){
@SerializedName("company_logo")
@Expose
val companyLogo: String? = null
....
}