如何使用 Swifty Json 将 POST 请求中的 JSON 数据保存到字典中? [英] How to save JSON data from a POST Request into dictionary with Swifty Json?

查看:37
本文介绍了如何使用 Swifty Json 将 POST 请求中的 JSON 数据保存到字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够在控制台中打印 json 数据,如下所示

I was able to print the json data in console which looks like this

{ 
    "created_at" : "2016-07-21 20:46:53",
    "name" : "PB Admin",
    "id" : 1,
    "updated_at" : "2016-07-21 12:46:53", 
    "lname" : "Admin",
    "access_lvl" : 1,
    "email" : "admin@admin.com",
    "fname" : "PB"
}

,但无法将其保存到字典中.

, but could not save it into a dictionary.

POST请求的方法

private func makeHTTPPostRequest(path: String, body: NSDictionary) {
    let request = NSMutableURLRequest(URL: NSURL(string: path)!)

    // Set the method to POST
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.HTTPMethod = "POST"

    do {
        // Set the POST body for the request
        let jsonBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
        request.HTTPBody = jsonBody
        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data!)
            print(json)//print on console

//i need to get the json data from here, but for some reason it would skip 
//this method
            self.parseJSON(json)
        })

        task.resume()
    } catch {
        // Create your personal error
        //onCompletion(nil, nil)
    }
}

这个方法应该将json数据保存到字典中

This method should save the json data into a dictionary

private func parseJSON(json: JSON) {

    for(_, object) in json {

        let createdAt = object["created_at"].stringValue
        let name = object["name"].stringValue
        let id = object["id"].stringValue
        let updatedAt = object["updated_at"].stringValue
        let lName = object["lname"].stringValue
        let accessLvl = object["access_lvl"].stringValue
        let email = object["email"].stringValue
        let fname = object["fname"].stringValue

        let obj = ["createdAt":createdAt, "name":name, "id":id, "updatedAt":updatedAt, "lName":lName, "accessLvl":accessLvl, "email":email, "fname":fname ]

        objects.append(obj)//wherein objects is a string dictionary
    }
}

每当我调试代码时,即使整个处理完成,对象字典也始终为空.

Whenever I debug the code, objects dictionary is always null even if the whole processed has finished.

推荐答案

您可以将您的 JSON 数据转换为 NSData,以便您可以轻松地从 NSData 而不是 JSON 中获取您的数据.

You can convert your JSON data to NSData so you can easly get yor data from NSData rather than JSON.

public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}

然后你可以创建一个像这样返回 NSDictionary 的函数:

Then you can create a function that returns NSDictionary like this:

func parseJSON(data: NSData) -> NSDictionary{
        var dic: NSDictionary!
        do {
            boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        } catch let error as NSError {
            print(error.localizedDescription)
            print("Error could not parse JSON data, it's null maybe?!!")
        }
        //'\(jsonStr)'

        return dic
    }

最后一:创建你的字典

let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary

希望有帮助.

这篇关于如何使用 Swifty Json 将 POST 请求中的 JSON 数据保存到字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆