简体   繁体   English

快速解析来自Anyobject的json

[英]Parsing json from Anyobject in swift

I am uploading image with SRWebClient library in swift. 我正在使用SRWebClient库快速上传图像。

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. 我正在从服务器返回json,我想解析它。 But I couldn't find how to parse json from AnyObject ? 但是我找不到如何从AnyObject解析json吗?

This code's ouput: 此代码的输出:

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

How can I parse this json in response variable ? 如何解析此json的response变量?

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: 我查看了您正在使用的库,从SRWebClient的第216-221 行中可以看到JSON序列化已为您完成:

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. 因此,使用已经解析的JSON对象调用成功 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 传递的状态HTTP状态代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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