如何在Kotlin中创建正确的JSON类(用于Fuel)

时间:2018-07-24 13:15:04

标签: android json kotlin

我有一个返回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,而不是“错误的电话号码”。

1 个答案:

答案 0 :(得分:0)

在研究了Fuel问题之后,我了解到,在大多数情况下,我们不需要编写自己的反序列化器,因为它们已经由 $("#test").on("click", function(){ var Clickvalue = $(this).text(); $("input").val(Clickvalue); search(Clickvalue); }); $("input").on( "input",function(){ console.log(this.value); search(this.value); }) var data_source = {1:"Tiger Nixon",2:"Garrett Winters"} function search(input){ var available_arr = []; for (var key in data_source){ if (data_source[key].indexOf(input) > 0){ available_arr.append(key); } } //function_you_use_for_construct_table(available_arr); } function function_you_use_for_construct_table(arr){ //blah blah... } 编写。

https://github.com/kittinunf/Fuel/issues/265中有一个示例。因此,只需将您的数据类放入Gson

<>

并通过

获取数据
URL.httpPost(listOf("name" to name, "phone" to phone)).responseObject<RegistrationResponse> ...

答案的旧版本

可能的障碍是列表反序列化,请参见
1. https://github.com/kittinunf/Fuel/issues/233
2. https://github.com/kittinunf/Fuel/pull/236

我认为,默认情况下,Fuel不使用Gson反序列化。

我仍然不知道如何对列表进行反序列化,但是通过此表达式获得了价值:

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