2017-02-08 71 views
0

目前我試圖從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) 
     } 
    }) 
    } 
} 
+0

您可以使用??檢查該變量。 Ex var strData = nil starData = strData ?? 「」 –

回答

0
guard let poster: String = "poster_path" <~~ json 

應該

guard let poster = ("poster_path" <~~ json) as? String 

(當然,你使用的是我一無所知庫,因此庫可以崩潰。 JSONSerialization是你的朋友,它的工作原理,每個人都知道它做了什麼)。

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. :) 
+1

歡迎來到Stack Overflow!請參閱[tour](http://stackoverflow.com/tour),查看並瀏覽[help center](http://stackoverflow.com/help),特別是 [我如何寫一個好的答案?](http://stackoverflow.com/help/how-to-answer)。請添加一些文字說明代碼的功能以及解決問題的原因。 –