2017-01-03 58 views
1

我有一個自定義對象:如何打印出下載後的自定義JSON對象值?

class SampleJSON { 

    var costDictionary: [String: Any] 
    var airbnbDetails: [String: Any] 
    var airbnbUS: Int 
    var airbnbLocal: Int 

    init(costDictionary: [String: Any], airbnbDetails: [String: Any], airbnbUS: Int, airbnbLocal: Int){ 

    self.costDictionary = costDictionary 
    self.airbnbDetails = airbnbDetails 
    self.airbnbUS = airbnbUS 
    self.airbnbLocal = airbnbLocal 
} 

init(resultsDictionary:[String: Any]){ 

    costDictionary = (resultsDictionary["cost"] as? [String: Any])! 
    airbnbDetails = (costDictionary["airbnb_median"] as? [String: Any])! 
    airbnbUS = (airbnbDetails["USD"] as? Int)! 
    airbnbLocal = (airbnbDetails["CHF"] as? Int)! 
} 

我想打印出對象的價值,他們已被下載後:

static func downloadAllTableViewData(urlExtension:String) -> [SampleJSON] { 

    var sampleJSON = [SampleJSON]()//array of custom object 

    let usm = UrlSessionNetworkManager.sharedManager 

    if let jsonDictionary = usm.parseJSONFromData(urlExtension:urlExtension) 

    { 
     let resultDictionaries = jsonDictionary["result"] as! [[String : Any]] 
     for resultsDictionary in resultDictionaries {// enumerate through dictionary 
     let nomadInfo = SampleJSON(resultsDictionary: resultsDictionary) 

     sampleJSON.append(nomadInfo) 
     } 
    } else { 
     print("Error: Cannot retrieve JSON Data") 
    } 

    print(sampleJSON) //Print Data here 

    return sampleJSON 
    } 
} 

我想打印出所有的值自定義對象的,但是當我嘗試使用打印(sampleJSON)我得到的打印出來,以控制檯

MyProject.SampleJSON

任何幫助表示讚賞!

+0

我想你應該在你自己的類的'init'之前打印'resultsDictionary'。 – JuicyFruit

回答

0

一個description變量添加到您的SampleJSON類,並使其符合CustomStringConvertible。例如:

class SampleJSON: CustomStringConvertible { 

    var costDictionary: [String: Any] 
    var airbnbDetails: [String: Any] 
    var airbnbUS: Int 
    var airbnbLocal: Int 

    init(costDictionary: [String: Any], airbnbDetails: [String: Any], airbnbUS: Int, airbnbLocal: Int){ 

    self.costDictionary = costDictionary 
    self.airbnbDetails = airbnbDetails 
    self.airbnbUS = airbnbUS 
    self.airbnbLocal = airbnbLocal 
    } 

    init(resultsDictionary:[String: Any]){ 

    costDictionary = (resultsDictionary["cost"] as? [String: Any])! 
    airbnbDetails = (costDictionary["airbnb_median"] as? [String: Any])! 
    airbnbUS = (airbnbDetails["USD"] as? Int)! 
    airbnbLocal = (airbnbDetails["CHF"] as? Int)! 
    } 

    var description: String { 
    return "SampleJSON(cost: \(self.costDictionary), airbnb: \(self.airbnbDetails), airbnb US: \(self.airbnbUS), airbnb local: \(self.airbnbLocal))" 
    } 
} 
+0

工作正常!我希望我早些時候知道這件事。謝謝你的幫助! – SwiftyJD