微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用带字典数组的Dictionary进行Swift JSON解析

我是使用 Swift语言进行iOS开发的初学者.我有一个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.我该如何修改这个方法.

您无法返回异步任务.你必须使用回调.

像这样添加一个回调:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐