使用ObjectMapper处理空JSON

时间:2017-08-09 19:10:50

标签: ios json swift google-api alamofire

我想知道如何处理来自JSON响应的空响应?

Alamofire Call

func getBooksWith(author: String, completion: @escaping (Result<[Book]>) -> Void) {
    let mainUrl = "\(ApiUrl.baseUrl)\(ApiUrl.endPoint)\(author)"
    print(mainUrl)
    guard let url = URL(string: mainUrl) else { return }
    Alamofire.request(url).responseArray(keyPath:"items") { (response:
        DataResponse<[Book]>) in
        switch response.result {
        case .success:
            if let books = response.result.value {
                DispatchQueue.main.async {
                    completion(.Succes(books))
                }
            }
        case .failure(let error):
            completion(.Error(error.localizedDescription))
        }
    }
}

因此函数返回一个Books数组,但缺少一些JSON数据,例如并非所有对象都有imgUrl或description

class Book: Mappable {

var title: String?
var authors: [String]?
var publishedDate: String?
var description: String?
var imgUrl: [String: AnyObject]?
var publisher: String?

required init?(map: Map) {

}

func mapping(map: Map) {
    publisher <- map["volumeInfo.publisher"] 
    title <- map["volumeInfo.title"]
    publishedDate <- map["volumeInfo.publishedDate"]
    description <- map["volumeInfo.description"]
    authors <- map["volumeInfo.authors"]
    imgUrl <- map["volumeInfo.imageLinks"]
    }
}

所以我所做的是在VC中调用updateUI func

func updateUI() {
    DispatchQueue.main.async {
        self.authorLabel.text = self.book?.authors?[0] ?? "Woops! No info!"
        self.publisherLabel.text = self.book?.publisher ?? "Woops! No info!"
        self.yearLabel.text = self.book?.publishedDate ?? "Woops! No info!"
        self.detailsLabel.text = self.book?.description ?? "Woops! No info!"
        guard let stringurl = self.book?.imgUrl?["thumbnail"] as? String else { return }
        guard let url = URL(string: stringurl) else { return }
        self.bookImageView.sd_setImage(with: url, placeholderImage: UIImage(named: "loadingImg"))
    }
}

简单地使用??,但我可以在任何其他更好的方式使用它吗? 例如,如何显示缺少某些数据的警报?

0 个答案:

没有答案