在swift中使用Optional解析JSON

时间:2016-06-02 08:14:13

标签: ios json swift parsing

Optional({"session":{"_id":"574fe96fa28f9aaadb000034","application_id":41262,"created_at":"2016-06-02T08:08:15Z","device_id":0,"nonce":21576,"token":"5b04f409c06ecf24ad2d9479a1ef7ef78916f864","ts":1464854895,"updated_at":"2016-06-02T08:08:15Z","user_id":0,"id":7274}})

我需要从上面的字典中解析并保存令牌(在Swift中)

我的要求是这样的:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            print("response = \(response)")

            let dict = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(dict)")
        }
        task.resume()

需要解析dict

2 个答案:

答案 0 :(得分:1)

在Swift 4中:

begin
    for i in 1..3 loop
        execute immediate 'drop table TEMP_EXP' || i;
    end loop;
end;

答案 1 :(得分:0)

JSON解析/映射可能既费时又费时。

我碰巧为它做了一个工具:

Jenerator

Download from here并转到/ usr / local / bin /

这是一个用Swift编写的小命令行工具,用于生成基于JSON的Swift模型。如果我通过它你的JSON它给了我这个:

import Foundation

struct SOSession {

    var created_at : String
    var _id : String
    var id : Int
    var device_id : Int
    var token : String
    var updated_at : String
    var nonce : Int
    var user_id : Int
    var ts : Int
    var application_id : Int

    init(data:[String:AnyObject]) {
        self.created_at = (data["created_at"] as? String) ?? ""
        self._id = (data["_id"] as? String) ?? ""
        self.id = (data["id"] as? Int) ?? 0
        self.device_id = (data["device_id"] as? Int) ?? 0
        self.token = (data["token"] as? String) ?? ""
        self.updated_at = (data["updated_at"] as? String) ?? ""
        self.nonce = (data["nonce"] as? Int) ?? 0
        self.user_id = (data["user_id"] as? Int) ?? 0
        self.ts = (data["ts"] as? Int) ?? 0
        self.application_id = (data["application_id"] as? Int) ?? 0
    }

    static func fromSource(urlString : String) -> SOSession? {
        guard let url = NSURL(string: urlString), data = NSData(contentsOfURL: url) else {
            return nil
        }
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            if let outerDict = json as? [String:AnyObject], let dict = outerDict["session"] as? [String:AnyObject] {
                return SOSession(data: dict)
            }
        } catch {}
        return nil
    }
}

获取令牌然后变得如此简单:

let myToken = SOSession.fromSource("someUrl")?.token

要使用Jenerator,我将JSON保存在桌面上的文件中并在终端中运行:

jenerator "$HOME/Desktop/so-1.json" StackOverflowQuestion1 SO

jenerator "path-to-file-with-json" save-file-name class-prefix

您现在可以将生成器代码复制到项目中。