如何解析从swift中的webservice返回的JSON

时间:2015-09-16 11:18:40

标签: json xcode swift web-services

嘿,我是swift的新手,我需要解析这个JSON并获取从webservice返回的“name”的值:

{name = "Sameer Hussain";}

到目前为止,这是我的代码:

    var url: NSURL = NSURL(string: "http://xxxxxxxxx.com/xxxxx/xxxx.php")!
    var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
    var bodyData = "data=something"
    request.HTTPMethod = "POST"
    //request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
            (response, data, error) in
           // println(data)
            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            //println(strData)
            var err1: NSError?
            var json2 = NSJSONSerialization.JSONObjectWithData(strData!.dataUsingEncoding(NSUTF8StringEncoding)!, options: .MutableLeaves, error:&err1 ) as! NSDictionary!
            println("\(json2)")
    }

1 个答案:

答案 0 :(得分:0)

从上面的代码看来,您的数据似乎正在json2变量中保存。要从该变量中检索值,您可以尝试这样的操作。

var userName: String?
var userAge: Int?
var userEmail: String?

if let parseJSON = json2
            {
                 userName = parseJSON["name"] as? String
                 userAge  = parseJSON["age"] as? Int
                 userEmail = parseJSON["email"] as? String
            }

如果返回的JSON看起来像这样,上面的内容就可以了:

            {
                "name": "John"
                "age": "21"
                "email": "john@gmail.com"

            }