将JsonObject解析为kotlin数据类

时间:2019-05-24 13:01:03

标签: android json kotlin android-volley data-class

我对Kotlin并不陌生,我正在尝试将我从JsonObject中获得的HTTPRequest解析为data class。但是我无法从Instance类中获得data

val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    Response.Listener { response ->
        val text = "Response: %s".format(response.toString())
        print(text)
    },
    Response.ErrorListener { error ->
        // TODO: Handle error
    }

)

@Throws(AuthFailureError::class)
@Override
fun getHeaders(): Map<String, String> {
    var params = HashMap<String, String>()
    if (params == null) params = HashMap()
    val basicAuth = "Basic " + Base64.encodeToString("username:password".toByteArray(), Base64.NO_WRAP);
    params["Authorization"] = basicAuth
    //..add other headers
    return params
}

TempJsonObject.instance?.addToRequestQueue(jsonObjectRequest)

数据类

data class TempJsonObject(
    val content: List<Content>) {
data class Content(
        val kioskId: Int,
        val location: Location,
        val stats: Stats,
        val settings: Settings,
        val modules: String,
        val visibility: String
) {
    data class Stats(
            val allLockers: Int,
            val emptyLockers: Int,
            val malfunctionLockers: Int,
            val forCustomer: Int,
            val forCourier: Int,
            val bySize: BySize,
            val incoming: Any
    ) {
        data class BySize(
                val XXSMALL: Xxsmall,
                val XSMALL: Xsmall,
                val SMALL: Small,
                val MEDIUM: Medium,
                val LARGE: Large,
                val XLARGE: Xlarge
        ) {
            data class Xxsmall(
                    val empty: Int,
                    val hasContent: Int
            )
        ...

我尝试做的方法是否正确,我在做错什么?

1 个答案:

答案 0 :(得分:0)

看着instance?.addToRequestQueue,这真让我感到困惑。我不知道像这样的Kotlin API解析JSON。我以为您使用的是添加了此类API的库,但是您也在注释中写道,由于缺少instance字段,因此代码无法编译。看起来它公开了数据类的某些单例实例。您能指出我使用该API的任何可行示例,还是您使用的其他任何来源?

如果以上情况都不正确,我将使用一些Kotlin或Java库将JSON解析为数据类的实例。一种选择是Kotlin库Klaxon:https://github.com/cbeust/klaxon。引用其中一个适合您的用例的示例:

val result = Klaxon().parse<Person>(""" { "name": "John Smith", } """)

assert(result?.name == "John Smith")
assert(result.age == 23)