【问题标题】:Retrofit returns 200 response code but I'm receiving null when accessing fields改造返回 200 响应代码,但我在访问字段时收到 null
【发布时间】:2021-05-04 00:51:33
【问题描述】:

我正在使用改造向 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 对象我没有得到 null 我已经坚持了两天了。任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • receive null when accessing field 是什么意思?值是返回 null 吗?
  • 它返回一个空值。但是响应代码是 200
  • 你和邮递员核实了吗?返回的结果有价值吗?因为如果结果与你的 POJO 不匹配,改造会抛出异常
  • 我已经更新了这个问题。尝试访问第二个对象data 时会出现问题。我已经发布了上面的截图
  • 你能把你的数据类BalanceResponse一起发帖吗?

标签: android kotlin mvvm retrofit2 dagger-hilt


【解决方案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
)

【讨论】:

  • 没问题的兄弟!很高兴它有帮助。但请务必在提问时提供详细信息:)
【解决方案2】:

你的班级应该按照json 命名,或者它应该提供@SerializedName 所以你的BalanceResponse 类应该是

data class BalanceResponse(
@SerializedName("data")
val balance: Balance,
@SerializedName("status")
val status: String
)

由于您试图将data 保存在balance 中,因此您必须提供SerializedName,但如果它们具有相同的名称且大小写完全相同,那么解析器将自动识别它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2021-01-02
    • 1970-01-01
    • 2020-02-09
    • 2012-03-09
    • 2020-09-26
    相关资源
    最近更新 更多