我尝试使用SwiftyJSON解析数据但由于某种原因我不断收到运行时错误。我用//中的代码中的错误,其中有2个。这是我尝试解析的数据示例:
result = {
cost = {
"airbnb_median" = {
CHF = 86;
USD = 86;
}
}
这是我在URLSession检索JSON后用来解析JSON的函数:
func parseJSONFromData(_ jsonData: Data?) -> JSON?
{
if let data = jsonData {
do {
let jsonDictionary = try JSON(data)
return jsonDictionary
} catch let error as NSError {
print("error processing json data: \(error.localizedDescription)")
}
}
return nil
}
这是我的自定义JSON对象:
class JSONObject {
var airbnbUS: Int
var airbnbLocal: Int
init(airbnbUS: Int, airbnbLocal: Int)
init(resultsDictionary:[String: Any]){
airbnbUS = (resultsDictionary["cost"]["airbnb_median"]["USD"] as? Int)!///Error Type 'Any?' has no subscript members
airbnbLocal = (resultsDictionary["cost"]["airbnb_median"]["CHF"] as? Int)!
}
这是我更新JSOn对象值的字典的方法:
static func updateResultsDictionary(urlExtension: String, completion:
@escaping (JSONObject?) -> Void) {
let nm = NetworkManager.sharedManager
_ = nm.getJSONData(urlExtension: urlExtension) {data in
guard let jsonDictionary = nm.parseJSONFromData(data),
let resultDictionaries = jsonDictionary["result"] //Error Initializer for conditional binding must have Optional type, not 'JSON'
else {
completion(nil)
return
}
for resultsDictionary in resultDictionaries {
let jsonInfo = JSONObject(resultsDictionary: resultsDictionary)
completion(jsonInfo)
}
}
}