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

前端之家收集整理的这篇文章主要介绍了使用带字典数组的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)
}
原文链接:https://www.f2er.com/swift/319614.html

猜你在找的Swift相关文章