无法访问从PHP脚本返回的json值

时间:2016-09-19 08:04:20

标签: ios json swift

我的PHP脚本返回响应,如

Optional({
    message = "";
    response =     {
        "session_id" = mf6pnrsf931m96g0hc3n4pjbw3;
        "session_name" = d72d1363f44031cac4148b0e6fa789d6;
    };
    "session_valid" = true;
    success = true;
})

如何在Swift 2.2中访问/打印会话ID /会话名称的值? 我在存储'session_valid'

返回的值时没有任何问题

2 个答案:

答案 0 :(得分:1)

     var parseObject: AnyObject?

    let data = NSData() //response data that you get from script(use this instead of "data"). if response is string then you need to convert the string to data


    do{
        parseObject = try NSJSONSerialization.JSONObjectWithData(data, options: [])
    }catch let error as NSError{
        print(error)
    }

    let objectDic = parseObject as! NSDictionary

    if let status = objectDic.objectForKey("success") as? Bool  {
        if status == true {
            if let validSession = objectDic.objectForKey("session_valid") as? Bool{

                if validSession {
                    let response = objectDic.objectForKey("response") as? NSDictionary

                    print(response)
                }

            }
        }

    }

答案 1 :(得分:0)

我需要的是这个 -

let response = objectDic.objectForKey("response") as? NSDictionary

接着是

let session_name = response.objectForKey("session_name") as! String