ios - 使用 Decodable 解码嵌套对象数组

标签 ios swift decodable

几天前我开始使用 Decodable,我想知道是否有可能在不创建任何更多模型的情况下创建模型“Car”,具有此 JSON:

{
    "cars": [
        {
            "id": 1,
            "name": "car1"
        },
        {
            "id": 2,
            "name": "car2"
        },
        {
            "id": 3,
            "name": "car3"
        }
    ],
    "pagination": {
        "page": 1,
        "offset": 20
    }
}

我找到的唯一解决方案是创建一个像“Response”这样的“wrappwer”模型,其中包含一个属性 [Cars]。

有人可以向我确认仅具有“Car”模型就可以解码这个 JSON 吗?

谢谢。

最好的问候

最佳答案

你可以试试

    let str = """

        {
        "cars": [
        {
        "id": 1,
        "name": "car1"
        },
        {
        "id": 2,
        "name": "car2"
        },
        {
        "id": 3,
        "name": "car3"
        }
        ],
        "pagination": {
        "page": 1,
        "offset": 20
        }
        }

    """


    do {

        let tr = try JSONSerialization.jsonObject(with: Data(str.utf8), options: []) as! [String:Any] 

        let da = try JSONSerialization.data(withJSONObject: tr["cars"]  , options: [])

        let res = try JSONDecoder().decode([Car].self, from: da)

        print(res)


    }
    catch {

        print(error)
    }

struct Car: Codable {
    let id: Int
    let name: String
}

关于ios - 使用 Decodable 解码嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54647795/

相关文章:

iOS 应用内支付 - 购买后向用户确认的正确方式是什么?

xcode - 通过 IBOutlet 与 Interface Builder 交互的 Swift 类

ios - 如何算法呢?

swift - 可解码符合枚举类型的属性

ios - Swift iOS 背景色 View animation as Timer

ios - React Native 响应式 View Iphone x

ios - 删除或卸载以前添加的库 : cocoapods

ios - 将相同的 UITableView 添加到不同的 ViewControllers

swift - 类型 'DBTweet' 不符合协议(protocol) 'Decodable'

使用 Decodable 协议(protocol)进行 JSON 解析