2
我是一個用iOS開發Swift語言的初學者。我有一個JSON文件包含如下的數據。Swift JSON解析字典與字典陣列
{
"success": true,
"data": [
{
"type": 0,
"name": "Money Extension",
"bal": "72 $",
"Name": "LK_Mor",
"code": "LK_Mor",
"class": "0",
"withdraw": "300 $",
"initval": "1000 $"
},
{
},
{
},
]
}
我想解析這個文件,並且必須返回包含JSON文件中的數據的字典。這是我寫的方法。
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParserForDataUsage(urlForData:String)->NSDictionary{
var dicOfParsedData :NSDictionary!
print("json parser activated")
let urlPath = urlForData
let endpoint = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL:endpoint!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
do {
guard let dat = data else {
throw JSONError.NoData
}
guard let dictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(dat, options:.AllowFragments) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(dictionary)
dicOfParsedData = dictionary
} catch let error as JSONError {
print(error.rawValue)
} catch {
print(error)
}
}.resume()
return dicOfParsedData
}
當我修改此方法返回字典時,它總是返回nil。我怎樣才能修改這個方法。
什麼是錯誤? –
@BlakeLockley用於定義端點的警戒聲明給我錯誤。我不知道如何解決它 – madhev
也許你的網址路徑格式錯誤?你可以和我們分享嗎? –