Search code examples
jsonswiftobjectdictionaryresponse

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]
completion(json)

then the completion looks like this:

(let json) in
if let dict = JSON{
    completion(dict)
}

and last completion looks like this:

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

problem is that, it returns object like this:

 {"created": "2016-06-01T10:49:54.096000",
 "data_source": "1",
 "display_name": "My Name",
 "email": "[email protected]",
 "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


Solution

  • try this :

    if let dictString = user as? String{
            if let data = dictString.dataUsingEncoding(NSUTF8StringEncoding){
    
                let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
                print(dic)
            }
    }