目前我試圖從JSON數據返回值,但遇到了其中一個值返回null從而導致我的應用程序崩潰的問題。如果json數組中的值返回null,如何返回下一個非空json值?
這是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)
}
})
}
}
您可以使用??檢查該變量。 Ex var strData = nil starData = strData ?? 「」 –