小编Bry*_*han的帖子

Swift 4 Decodable:来自嵌套数组的struct

鉴于以下JSON文档,我想创建一个struct包含四个属性:filmCount(Int),year(Int),category(String)和actor(Actor数组).

{    
    "filmCount": 5,
    "year": 2018,
    "category": "Other",
    "actors":{  
        "nodes":[  
            {  
                "actor":{  
                    "id":0,
                    "name":"Daniel Craig"
                }
            },
            {  
                "actor":{  
                    "id":1,
                    "name":"Naomie Harris"
                }
            },
            {  
                "actor":{  
                    "id":2,
                    "name":"Rowan Atkinson"
                }
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

PlacerholderData是一个存储三个主要属性和actor列表的结构,这些属性应该从JSON对象nodesactors属性中的嵌套容器中检索.

PlacerholderData:

struct PlaceholderData: Codable {
    let filmCount: Int
    let year: Int
    let category: String
    let actors: [Actor]
}
Run Code Online (Sandbox Code Playgroud)

Actor.swift:

struct Actor: Codable {
    let id: Int
    let name: String
} …
Run Code Online (Sandbox Code Playgroud)

json swift codable decodable

7
推荐指数
1
解决办法
2301
查看次数

标签 统计

codable ×1

decodable ×1

json ×1

swift ×1