How to save JSON data from a POST Request into dictionary with Swifty Json?

≯℡__Kan透↙ 提交于 2019-12-25 04:45:12

问题


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.

The method for POST request

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

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.


回答1:


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

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
    }

Last One: Create your dictionary

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

Hope it helps.




回答2:


let jsonDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary



来源:https://stackoverflow.com/questions/38559403/how-to-save-json-data-from-a-post-request-into-dictionary-with-swifty-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!