如何以以下格式获取JSON文件:
https://developers.themoviedb.org/3/people/get-popular-people
Alamofire用于从在线数据库中获取数据。
我不知道确切如何格式化收到的JSON文件,因此嵌套数组可以将元素保存在实例MovieModel中(海报:UIImage, 名称:字符串, 等级:双倍 年:字符串, posterLink:字符串, id:Int)
错误:致命错误:NSArray元素与Swift Array元素类型不匹配
我的代码如下:
class MovieModel {
private var _poster: UIImage!
private var _background: UIImage!
private var _name: String! // original_title
private var _overview: String! // overview
private var _rating: Double! // vote_average
private var _year: String!
private var _posterLink: String!
private var _backgroundLink: String!
private var _genres: [Int]!
private var _id: Int!
init(poster: UIImage,
name: String,
rating: Double,
year: String,
posterLink: String,
id: Int){
_poster = poster
_name = name
_rating = rating
_year = year
_posterLink = posterLink
_id = id
getPosterImage()
}
}
class ActorModel {
private var _poster : UIImage!
private var _birthday : String?
private var _known_for_department : String?
private var _deathday : String?
private var _id : Int!
private var _known_for : [MovieModel]?
private var _name : String!
private var _also_known_as : [String]!
private var _gender : Int!
private var _biography : String?
private var _popularity : Double?
private var _place_of_birth : String?
private var _profile_path : String?
private var _adult : Bool!
private var _imdb_id : String!
private var _homepage : String!
init(poster : UIImage, id : Int, known_for: [MovieModel], name: String, popularity : Double, profile_path : String) {
_poster = poster
_id = id
_known_for = known_for
_name = name
_popularity = popularity
_profile_path = profile_path
getPosterImage()
}
}
func getPopularActors(){
let url = BASE_URL + "/person/popular?" + API_KEY + LANG + "&page=1"
self.actorList = []
Alamofire.request(url).responseJSON {response in
if let result = response.result.value as? Dictionary<String,Any> {
if let list = result["results"] as? [Dictionary<String,Any>] {
for i in list {
self.actorList.append(ActorModel(
poster: UIImage(),
id: i["id"] as! Int,
known_for: i["known_for"] as! [MovieModel],
name: i["name"] as! String,
popularity: i["popularity"] as! Double,
profile_path: "\(self.IMAGE_URL)\(i["profile_path"] as! String)"
))
}
if let del = self.actorDelegate {
del.transferActors(data: self.actorList)
}
}
}
}
}
答案 0 :(得分:0)
您应该为此真正使用Decodable。但是以您当前的解决方案为基础:
for i in list {
var movieModels = [MovieModel]()
if let knownForArray = i["_known_for"] as? [[String: Any]] {
for knownFor in knownForArray {
movieModels.append(MovieModel(
poster: UIImage(),
name: knownFor["name"] as! String,
rating: knownFor["rating"] as! Double,
... //And so on
))
}
}
self.actorList.append(ActorModel(
poster: UIImage(),
id: i["id"] as! Int,
known_for: movieModels,
name: i["name"] as! String,
popularity: i["popularity"] as! Double,
profile_path: "\(self.IMAGE_URL)\(i["profile_path"] as! String)"
))
}