nikagar4 nikagar4 - 1 year ago 82
JSON Question

Can't create dictionary from json in swift

I Have this json object which is downloaded by dataTaskWithRequest, i download it and serialize it like this:

let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String:AnyObject]

then the completion looks like this:

(let json) in
if let dict = JSON{

and last completion looks like this:

(let response) in
if let resp = response{
if resp["status"] as? Int == 0{
let user = resp["user"]
if let dict = user{

problem is that, it returns object like this:

{"created": "2016-06-01T10:49:54.096000",
"data_source": "1",
"display_name": "My Name",
"email": "",
"fb_id": "",
"first_name": "My",
"gender": "0",
"google_id": "",
"id": "SomeId",
"last_name": "Name",
"phone": "Number",
"updated": "2016-06-01T10:49:54.096000"}

when i try to cast this object in [String:AnyObject] it returns nil, and i can't get the values from this last object, can anybody help me with this, i've been trying to do this for like 4 hours and couldn't get it done

Answer Source

try this :

if let dictString = user as? String{
        if let data = dictString.dataUsingEncoding(NSUTF8StringEncoding){

            let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download