如何在下载后打印自定义JSON对象值?

时间:2017-01-03 23:30:03

标签: json swift nsurlsession

我有一个自定义对象:

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
  }
}

我正在尝试打印出自定义对象的所有值,但是当我尝试使用print(sampleJSON)时,我打印到控制台的所有值都是

  

MyProject.SampleJSON

感谢任何帮助!

1 个答案:

答案 0 :(得分: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))"
  }
}