目前我正在尝试从JSON数据返回值,但遇到的问题是其中一个值返回null,从而导致我的应用程序崩溃。
这就是json的样子:
"results": [
{
"genre_ids": [
99
],
"id": 440108,
"poster_path": null, //The value that's causing incredible headaches!
},
{
"genre_ids": [
99,
10402
],
"id": 391698,
"poster_path": "/uv7syi4vRyjvWoB8qExbqnbuCu5.jpg",//The value trying to get!
},
]
我正在使用json对象映射器Gloss,这对于这一点已经很好了。以下是我设置对象的方法:
public struct ResultsGenrePosters: Decodable {
public let results : [GenrePosters]?
public init?(json: JSON) {
results = "results" <~~ json
}
}
public struct GenrePosters: Decodable, Equatable{
public let poster : String
public init? (json: JSON) {
guard let poster: String = "poster_path" <~~ json
else {return nil}
self.poster = poster
}
public static func ==(lhs: GenrePosters, rhs: GenrePosters) -> Bool {
return lhs.poster == rhs.poster
}
static func updateGenrePoster(genreID: NSNumber, urlExtension: String, completionHandler:@escaping (_ details: [String]) -> Void){
let nm = NetworkManager.sharedManager
nm.getJSONData(type:"genre/\(genreID)", urlExtension: urlExtension, completion: {
data in
if let jsonDictionary = nm.parseJSONData(data)
{
guard let genrePosters = ResultsGenrePosters(json: jsonDictionary)
else {
print("Error initializing object")
return
}
guard let posters = genrePosters.results
else {
print("No poster exists for genre: \(genreID)")// This keeps on triggering when the null object is hit, this is where it would be good to move to the next array to get that value
return
}
let postersArray = posters.map {$0.poster}// converts custom object "GenrePosters" to String(poster value)
completionHandler(postersArray)
}
})
}
}
答案 0 :(得分:0)
guard let poster: String = "poster_path" <~~ json
应该是
guard let poster = ("poster_path" <~~ json) as? String
(当然你使用的是我一无所知的库,所以库可能会崩溃.JSONSerialization是你的朋友。它的工作原理。每个人都知道它的作用)。
答案 1 :(得分:0)
for data in results as! [Dictionary<String,AnyObjects>]{
var value1 = data["key"] as? String
if value1 == nil{value1 = ""}else{}
}
}
That was just a simple logic but completely work for me all the time. :)