我正在调用 API 端点,JSON 响应如下所示:
{
"id": 299536,
"cast": [
{
"cast_id": 1,
"character": "Tony Stark / Iron Man",
"credit_id": "54a9cfa29251414d5b00553d",
"gender": 2,
"id": 3223,
"name": "Robert Downey Jr.",
"order": 0,
"profile_path": "/1YjdSym1jTG7xjHSI0yGGWEsw5i.jpg"
},
{
"cast_id": 6,
"character": "Thor Odinson",
"credit_id": "54a9d012c3a3680c29005762",
"gender": 2,
"id": 74568,
"name": "Chris Hemsworth",
"order": 1,
"profile_path": "/lrhth7yK9p3vy6p7AabDUM1THKl.jpg"
},
{
"cast_id": 13,
"character": "Bruce Banner / Hulk",
"credit_id": "573fc00592514177ec00010a",
"gender": 2,
"id": 103,
"name": "Mark Ruffalo",
"order": 2,
"profile_path": "/isQ747u0MU8U9gdsNlPngjABclH.jpg"
}
]
这是我为可编码协议(protocol)制作的结构。
struct MovieCast: Codable {
let id: Int
let cast: [Cast]
let crew: [Crew]
}
struct Cast: Codable {
let castID: Int
let character, creditID: String
let gender, id: Int
let name: String
let order: Int
let profilePath: String?
enum CodingKeys: String, CodingKey {
case castID = "cast_id"
case character
case creditID = "credit_id"
case gender, id, name, order
case profilePath = "profile_path"
}
}
struct Crew: Codable {
let creditID: String
let department: Department
let gender, id: Int
let job, name: String
let profilePath: String?
enum CodingKeys: String, CodingKey {
case creditID = "credit_id"
case department, gender, id, job, name
case profilePath = "profile_path"
}
}
enum Department: String, Codable {
case art = "Art"
case camera = "Camera"
case costumeMakeUp = "Costume & Make-Up"
case crew = "Crew"
case directing = "Directing"
case editing = "Editing"
case lighting = "Lighting"
case production = "Production"
case sound = "Sound"
case visualEffects = "Visual Effects"
case writing = "Writing"
}
我的问题是,如何使用 Swift 4 循环遍历单个数组中的对象?我正在使用 Decodable 协议(protocol),并且结构如下所示:(请注意,我在上面列出了一些 json 响应属性,因此代码片段不会太长)
我的目标是获得
profile_path
从每个对象中取出并将其附加到字符串数组中。
最佳答案
收到响应后,在 viewDidLoad()
中尝试此代码
if let dict = response.result.value as? [string:Anyobject]() //fetching the response
if let innerdict = dict["cast"] as? [[string:Anyobject]]()
for cast in innerdict {
if let profile_path = cast[ "profile_path"] as? String
print("profile_path") // to check the profilepath
}
//这是获取配置文件路径然后将其附加到字符串类型数组中
关于ios - 如何解析单个 JSON 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240259/