动态 JSON 响应解析为 GSON 模型 - 具有动态数据类型的动态密钥

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

我的 JSON 响应结构如下:

{
    "status": true,
    "data": {
        "Owner": {
            "owner_name": "name",
            "title": "Standup meeting",
            "description": "..."
            // Other fields
        },
        "Moderator": [
            {
                "owner_name": "name",
                "title": "Standup meeting",
                "description": "..."
                // Other fields
            }
            // Potentially more objects in the array
        ]
        // Potentially more dynamic keys with objects or arrays of objects
    }
}

在此 JSON 响应中,有各种动态键,例如“所有者”和“主持人”,每个键都包含一个 JSON 对象或一个 JSON 对象数组。我需要创建一个 GSON 数据类来解析这个动态 JSON 响应。

我目前遇到以下数据类,不确定它是否正确:

data class MineMeetResponse(
    @SerializedName("status")
    val status: Boolean,
    @SerializedName("data")
    val data: HashMap<String, ...>
)

我不确定上述数据模型是否正确。您能帮我为这个动态 JSON 响应创建一个 GSON 模型吗?

此外,我非常感谢有关为此数据模型编写单元测试用例的指导。您在创建数据模型和建议单元测试策略方面的帮助将会非常有帮助。

android json gson retrofit2
1个回答
0
投票

如果将 Data 标签中的所有对象类型定义如下并使其可为空。

data class MineMeetResponse (
        val status: Boolean,
        val data: Data
        )
    
data class Data (
            val owner: Owner? = null,
            val moderator: List<Owner>? = null,
            // more types here...
        )
        
data class Owner (
            val ownerName: String,
            val title: String,
            val description: String,
            // Other fields as nullable...
            // val foo: T? = null 
        )
© www.soinside.com 2019 - 2024. All rights reserved.