如何使用自定义语法化解析JSON数据

k97glaaz  于 2023-10-21  发布在  其他
关注(0)|答案(2)|浏览(113)

我正在发送API调用并得到这样的响应

{ "12312412312124123124": { "id": "12312412312124123124", "content": [ { "id": 41419969} ] },
"141412312412312521": { "id": 141412312412312521", "content": [ { "id": 41419969} ] }}

我如何处理解析这个json对象或为它创建数据类,我已经搜索了自定义封装,但找不到答案.
这是我的调用执行代码

builder.build().newCall(request).execute().use { response ->

        if (response.isSuccessful) {
            val responseBody = response.body?.string()
          
            if (!responseBody.isNullOrBlank()) {
                val readings = gson.fromJson(responseBody, MyClassForParsing::class.java)
                
            } else {
                println("Response body is empty.")
            }
        } else {
            println("Request failed with code: ${response.code}")
        }
    }
qcbq4gxm

qcbq4gxm1#

我用reflection来做网络。你也可以把json转换成变量
你可以在这里阅读:https://betterprogramming.pub/how-to-use-retrofit-for-networking-in-android-for-beginners-ef6bae5ef113

cidc1ykv

cidc1ykv2#

响应数据类(不要忘记添加@SerializedName

data class ResponseType(
    var id: String?,
    var content: List<Content>?
)

data class Content(
    var id: Int?
)

变量键值在相关JSON数据中可用

interface API {
    @GET("yourEndPoint")
    fun yourFunction(): Call<HashMap<String, ResponseType>>
}

最后一步呼叫排队

val call = service.getYourApiRequestFunction()

call.enqueue(object : Callback<HashMap<String, ResponseType>> {
    override fun onResponse(
        call: Call<HashMap<String, ResponseType>>,
        response: Response<HashMap<String, ResponseType>>
    ) {
        if (response.isSuccessful) {
            val responses = response.body()
            // your process - responses type ==== > HashMap<String, ResponseType>
        }
    }

    override fun onFailure(call: Call<HashMap<String, ResponseType>>, t: Throwable) {
        // your error case
    }
})

相关问题