[英]How to parse a single JSON array of objects?
我正在调用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"
}
]
这是我为可编码协议编写的结构。
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协议,并具有如下所示的结构:(请注意,我忽略了上面的一些json响应属性,因此代码段不会太长)
我的目标是
profile_path
从每个对象中提取出来并将其附加到字符串数组中。
MovieCast结构包含2个数组,其中1个是Cast
对象,而2个是Crew
对象。
您可以创建一个具有两个属性( gender
, name
, profilePath
)共享的协议Staff
,声明两种类型都符合该协议,然后将Cast
和Crew
对象数组组合成Staff
数组。
然后,您可以将结果数组从数组中每个条目的profilePath
值映射到字符串数组:
protocol Staff {
var gender: Int { get }
var name: String { get }
var profilePath: String? { get }
}
像这样更改Cast和Crew:
struct Cast: Codable & Staff
struct Crew: Codable & Staff
如果您有船员:
var movieCrew: MovieCast
//Code to load a moview crew
然后
let castAndCrew = (movieCrew.cast as [Staff]) + ((movieCrew.crew as [Staff]?) ?? [])
let allProfilePaths = castAndCrew.compactMap { $0.profilePath }
(请注意,我是在SO编辑器中键入此命令的,而我的语法很少“完美”。它可能需要进行一些小的清理。)
得到响应后,请在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
}
//这是获取配置文件路径,然后将其追加到string类型的数组中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.