如何通过自定义反序列化解析Json数据

问题描述 投票:0回答:3

我正在发送 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}")
        }
    }
android json kotlin networking retrofit
3个回答
1
投票

我正在使用改造来建立网络。你也可以将 json 处理为变量

你可以在这里阅读:https://betterprogramming.pub/how-to-use-retrofit-for-networking-in-android-for-beginners-ef6bae5ef113


0
投票

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

@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
    }
})

0
投票

我找到了答案,如果它对某人有帮助,我会将其发布在这里......

首先你需要获取响应 JsonObject ,如下所示:

suspend fun yourFunction() : JsonObject

然后你需要将该 JsonObject 存储在变量中

val call = service.yourFunction()

那你需要这个功能

 fun parseStringParameterWithGsonKotlinDynamicKey(stringParameter: String): Map<String, Any?> {
    val gson = Gson()
    val jsonObject = gson.fromJson(stringParameter, JsonObject::class.java)

    val parsedParameters = mutableMapOf<String, Any?>()
    for ((key, value) in jsonObject.entrySet()) {
        parsedParameters[key] = value
    }

    return parsedParameters
}

创建另一个变量并调用此函数,将 JsonObject 作为 String 传递,就像这样

val dfg= parseStringParameterWithGsonKotlinDynamicKey(call.toString())

此时,您将获得解析后的 json 对象,其中包含您的对象,您可以像这样迭代并获取您的项目

dfg.entries.forEach { item ->
       val devices = Gson().fromJson(item.value.toString(),YuorDataClass::class.java)
   }

我希望有人能找到答案,我会让某人开心!

附注谢谢回复!

© www.soinside.com 2019 - 2024. All rights reserved.