我正在使用改造向 API 发出网络请求。响应代码返回 200,但我在尝试访问字段时收到 null
。我已经检查了其他解决方案,但似乎无法解决我的问题。我正在使用 hilt
这是我的 API 类
interface BlockIOApi{
@GET("/api/v2/get_balance/")
suspend fun getBalance(
@Query("api_key")
apiKey: String = BuildConfig.API_KEY
): Response<BalanceResponse>
}
这是我的应用模块对象
<块引用>应用模块
@Module
@InstallIn(ApplicationComponent::class)
object AppModule{
@Singleton
@Provides
fun provideOkHttpClient() = if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
} else OkHttpClient
.Builder()
.build()
@Provides
@Singleton
fun providesRetrofit(okHttpClient: OkHttpClient): Retrofit =
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
@Provides
@Singleton
fun providesApiService(retrofit: Retrofit): BlockIOApi = retrofit.create(BlockIOApi::class.java)
}
最后这里是我的存储库,DefaultRepository.kt
class DefaultRepository @Inject constructor(
private val blockIOApi: BlockIOApi,
private val balanceDao: BalanceDao
):BlockIORepository {
override suspend fun getBalance(): Resource<BalanceResponse> {
return try {
val response = blockIOApi.getBalance()
Log.d("TAG", "getBalance>>Response:${response.body()?.balance} ")
if (response.isSuccessful){
response.body().let {
return@let Resource.success(it)
}
}else{
Log.d("TAG", "getBalance: Error Response >>> ${response.message()}")
Resource.error("An unknown error occured",null)
}
}catch (ex :Exception){
Resource.error("Could not reach the server.Check your internet connection",null)
}
}
还有这个接口,BlockIORepository.kt
interface BlockIORepository {
suspend fun getBalance(): Resource<BalanceResponse>
suspend fun insertBalance(balance: Balance)
suspend fun getCachedBalance(): Balance
suspend fun getAddresses(): Resource<DataX>
}
这是我的数据类
data class BalanceResponse(
val balance: Balance,
val status: String
)
@Entity
data class Balance(
val available_balance: String,
val network: String,
val pending_received_balance: String,
@PrimaryKey(autoGenerate = false)
var id: Int? = null
)
当我尝试访问
data
对象时出现问题。我没有为 status
对象获取空值
我已经坚持了两天了。任何帮助将不胜感激。提前致谢。
答案 0 :(得分:1)
您的班级应根据 json
命名或应提供 @SerializedName
所以你的 BalanceResponse
类应该是
data class BalanceResponse(
@SerializedName("data")
val balance: Balance,
@SerializedName("status")
val status: String
)
由于您试图将 data
保存在 balance
中,因此您必须提供 SerializedName
,但如果它们具有相同的名称且大小写相同,那么解析器将自动识别它们。
答案 1 :(得分:1)
问题出现在这里:
data class BalanceResponse(
val balance: Balance, <-- in postman it is "data"
val status: String
)
您应该考虑为您的班级添加 @SerializedName(xxx)
。
data class BalanceResponse(
@SerializedName("data") val balance: Balance,
val status: String
)