{ "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.我该如何修改这个方法.
您无法返回异步任务.你必须使用回调.像这样添加一个回调:
completion: (dictionary: NSDictionary) -> VoID
到您的解析器方法签名:
func JsonParserForDataUsage(urlForData: String,completion: (dictionary: NSDictionary) -> VoID)
并调用您想要“返回”的数据可用的完成:
func JsonParserForDataUsage(urlForData: String,completion: (dictionary: NSDictionary) -> VoID) { print("Json parser activated") let urlPath = urlForData guard let endpoint = NSURL(string: urlPath) else { return } let request = NSMutableURLRequest(URL:endpoint) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data,error) -> VoID in do { guard let dat = data else { throw JsONError.NoData } guard let dictionary = try NSJsONSerialization.JsONObjectWithData(dat,options:.AllowFragments) as? NSDictionary else { throw JsONError.ConversionFailed } completion(dictionary: dictionary) } catch let error as JsONError { print(error.rawValue) } catch let error as NSError { print(error.deBUGDescription) } }.resume()}
现在,您可以将此方法与尾随闭包一起使用以获取“返回”值:
JsonParserForDataUsage("http...") { (dictionary) in print(dictionary)}总结
以上是内存溢出为你收集整理的使用带字典数组的Dictionary进行Swift JSON解析全部内容,希望文章能够帮你解决使用带字典数组的Dictionary进行Swift JSON解析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)