Here is my JSON

{
    "id": 1,
    "user": {
        "user_name": "Tester",
        "real_info": {
            "full_name":"Jon Doe"
        }
    },
    "reviews_count": [
        {
            "count": 4
        }
    ]
}

Here is the structure I want it saved to (incomplete)

struct ServerResponse: Decodable {
    var id: String
    var username: String
    var fullName: String
    var reviewCount: Int

    enum CodingKeys: String, CodingKey {
       case id, 
       // How do i get nested values?
    }
}

I have looked at Apple's Documentation on decoding nested structs, but I still do not understand how to do the different levels of the JSON properly. Any help will be much appreciated.

推荐答案

另一种方法是创建一个与JSON紧密匹配的中间模型(借助quicktype.io这样的工具),让Swift生成解码方法,然后在最终的数据模型中 Select 所需的部分:

// snake_case to match the JSON and hence no need to write CodingKey enums / struct
fileprivate struct RawServerResponse: Decodable {
    struct User: Decodable {
        var user_name: String
        var real_info: UserRealInfo
    }

    struct UserRealInfo: Decodable {
        var full_name: String
    }

    struct Review: Decodable {
        var count: Int
    }

    var id: Int
    var user: User
    var reviews_count: [Review]
}

struct ServerResponse: Decodable {
    var id: String
    var username: String
    var fullName: String
    var reviewCount: Int

    init(from decoder: Decoder) throws {
        let rawResponse = try RawServerResponse(from: decoder)

        // Now you can pick items that are important to your data model,
        // conveniently decoded into a Swift structure
        id = String(rawResponse.id)
        username = rawResponse.user.user_name
        fullName = rawResponse.user.real_info.full_name
        reviewCount = rawResponse.reviews_count.first!.count
    }
}

This also allows you to easily iterate through reviews_count, should it contain more than 1 value in the future.

Json相关问答推荐

盒子图显示不正确

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

将PostgreSQL转换为JSON对象

JOLT转换以根据条件删除json对象

JOLT转换以基于对象属性过滤JSON数组

规范化JSON数据

震动范围改善

如何在 Android Studio 中将 List 字段作为空列表[]返回?

如果 JSON 对象包含列表中的子字符串,则丢弃它们

在 postgresql 中将行转换为 json 对象

如何在生产环境中更改 Flutter 应用程序中的数据模型?

C# 合并 2 个几乎相同的 JSON 对象

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

Python Flask-Restful POST 不采用 JSON 参数

使用 jq,将对象数组转换为具有命名键的对象

在 JSON 对象中强制执行非空字段

as_json 没有在关联上调用 as_json

python追加到json对象中的数组

将 JsonArray 添加到 JsonObject