Fuel Expected Begin Array但是Begin Object

时间:2018-04-16 11:28:06

标签: android kotlin deserialization response

我是Kotlin的新手,我还在学习如何获得一个对象,但我有以下例外:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

这是Json结果:

{"Success":"1","Message":"True","Items":[{"Id":3,"Name":"AndroidVersion","Value":"1"},{"Id":4,"Name":"IOSVersion","Value":"1.0"},{"Id":5,"Name":"AndroidForceUpdate","Value":"true"}]}

这是模型类

data class MobileConfiguration(
    val id: Int,
    val name: String,
    val value: String
) {


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

}

这是电话:

url.httpPost(listOf(Pair("key", ""))).responseObject(MobileConfiguration.Deserializer()) { request, response, result ->

        //val (people, err) = result.get()
        when (result) {
            is Result.Failure -> {
                val ex = result.getException()
                Log.wtf("ex", "is " + ex)
            }
            is Result.Success -> {

                val (config, err) = result
                //Add to ArrayList
                config?.forEach { configuration ->
                    mobileConfigurations.add(configuration)
                }

                println(mobileConfigurations)
            }
        }
    }

如果有人可以提供帮助,我做错了什么

1 个答案:

答案 0 :(得分:0)

我认为问题出在模型类中。 您假设MobileConfiguration数组直接位于响应类下,但实际上,它位于Items对象下。

因此,不应将Array<MobileConfiguration>用作responseObject,而应将其他类用作容器,如:

data class MobileConfigurationResponse(
    val success: String,
    val message: String,
    val items: Array<MobileConfiguration>
)

然后你就可以得到这样的数组:

    val (config, err) = result.items