簡體   English   中英

如何在Kotlin中創建正確的JSON類(用於Fuel)

[英]How to create a right JSON class in Kotlin (for Fuel)

我有一個返回JSON的請求:

{
  "success": 0,
  "errors": {
    "phone": [
      "Incorrect phone number"
    ]
  }
}

我插入了Fuel而不是Kotlin的Retrofit。 因此,我的課程是:

data class RegistrationResponse(
    val success: Int,
    val errors: RegistrationErrorsResponse?) {

    class Deserializer : ResponseDeserializable<RegistrationResponse> {
        override fun deserialize(content: String): RegistrationResponse? =
            Gson().fromJson(content, RegistrationResponse::class.java)
    }
}

data class RegistrationErrorsResponse(val phone: List<String>?) {

    class Deserializer : ResponseDeserializable<RegistrationErrorsResponse> {
        override fun deserialize(content: String): RegistrationErrorsResponse? =
            Gson().fromJson(content, RegistrationErrorsResponse::class.java)
    }
}

請求看起來像:

class Api {

    init {
        FuelManager.instance.basePath = SERVER_URL
    }

    fun registration(name: String, phone: String): Request =
        "/registration/"
            .httpPost(listOf("name" to name, "phone" to phone))
}

private fun register(name: String, phone: String) {
    Api().registration(name, phone)
        .responseObject(RegistrationResponse.Deserializer()) { _, response, result ->
            val registrationResponse = result.component1()
            if (registrationResponse?.success == 1) {
                showScreen()
            } else {
                showErrorDialog(registrationResponse?.errors?.phone?.firstOrNull())
            }
        }
}

一個問題是,發生錯誤時,數據類(registrationResponse?.errors?.phone)中的phone變量將填充為null ,而不是“錯誤的電話號碼”。

在研究了Fuel問題之后,我了解到,在大多數情況下,我們不需要編寫自己的反序列化器,因為它們已經由Gson編寫。

https://github.com/kittinunf/Fuel/issues/265中,有一個示例。 因此,只需將您的數據類放在<>

URL.httpPost(listOf("name" to name, "phone" to phone)).responseObject<RegistrationResponse> ...

並通過獲取數據

result.component1()?.errors?.phone?.firstOrNull()

舊版本的答案

列表反序列化可能是一個障礙,請參閱
1. https://github.com/kittinunf/Fuel/issues/233
2. https://github.com/kittinunf/Fuel/pull/236

我認為,默認情況下,Fuel不使用Gson反序列化。

我仍然不知道如何反序列化列表,但是通過以下表達式得到了值:

((result.component1().obj()["errors"] as JSONObject).get("phone") as JSONArray)[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM