简体   繁体   中英

Parsing json from Anyobject in swift

I am uploading image with SRWebClient library in swift.

My code:

func uploadImage() {
    let imageData:NSData = UIImageJPEGRepresentation(profilePicture.image, 100)
    SRWebClient.POST("url")
        .data(imageData, fieldName:"imagefile", data: ["username":self.username,"key":self.token])
        .send({(response:AnyObject!, status:Int) -> Void in
            println("result: \(response)")
            //I have to parse result variable in here
            },failure:{(error:NSError!) -> Void in

        })
}

Actually it works well. I am returning json from my server and I want to parse it. But I couldn't find how to parse json from AnyObject ?

This code's ouput:

{"status":1,"picture":"e8ca745f511e8104fe2f920aab5d09c6.jpg"}

How can I parse this json in response variable ?

if let json = response as? [String : AnyObject] {
    for key in json.keys {
        if let intValue = json[key] as? Int {
            // json[key] is an Int. Do something with intValue
        } else if let stringValue = json[key] as? String {
            // json[key] is a String. Do something with stringValue
        }
    }
}

I looked at the lib you are using and you can see, from line 216 - 221 in SRWebClient that the JSON serialization is done for you:

let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(result!, options: nil, error: &error)
                    if (error != nil && failure != nil) {
                        failure!(error)
                    } else if (json != nil && success != nil) {
                        success!(json, httpResponse!.statusCode)
                    }

So success is called with an already parsed JSON object. Try to cast it to a dictionary like this:

if let jsonResponse = response as? [String: AnyObject] {
  // do whatever needs to be done with the dictionary here
}

And the status passed is a HTTP Status Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM