JSON解析的数据没有被调用?迅速

时间:2015-09-06 06:39:02

标签: ios json swift

我已经从API中解析了我的数据但是当我尝试从解析的NSDictionary数据中设置一些值时,不会调用println语句。它发生在带有“user”键的字典中,我尝试设置学生的名字和姓氏。

func getUserData(hostViewController: UIViewController ) {
        if self.userID == nil{
            println("User ID is nil")
        }
        else {
        var key = self.userID
        let urlString = UdacityClient.Constants.BaseURLSecure + "/users" + "/\(key)"
        println(urlString)
        let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
        let request = NSMutableURLRequest(URL: url!)


        let task = session.dataTaskWithRequest(request) {data, response, error in
            if error != nil {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    println(error)
                    let alertController = UIAlertController(title: "Oh no", message: "Error in User Data", preferredStyle: UIAlertControllerStyle.Alert)

                    let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in
                        hostViewController.dismissViewControllerAnimated(true, completion: nil)
                    })
                    alertController.addAction(cancelAction)

                    hostViewController.presentViewController(alertController, animated: true, completion: nil)
                })

                println("Error in User Data")

            }  else {
                let newData = data.subdataWithRange(NSMakeRange(5, data.length - 5))
                var parsingError: NSError? = nil
                let parsedResult = NSJSONSerialization.JSONObjectWithData(newData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as! NSDictionary


                if let userDictionary = parsedResult["user"] as? [String: AnyObject] {
                    if let firstName = userDictionary["first_name"] as? String {
                        self.firstName = firstName
                        println("This is not printing ")
                        println(firstName)
                    }
                }

                if let userDictionary = parsedResult["user"] as? [String: AnyObject] {
                    if let lastName = userDictionary["last_name"] as? String {
                        self.lastName = lastName
                        println("This is not printing also")
                        println(lastName)
                    }
                }

                if let err = parsingError {
                    dispatch_async(dispatch_get_main_queue(),{ () -> Void in
                        println(err)
                        let alertController = UIAlertController(title: "Oh no", message: "Error in Parsing User Data from Udacity", preferredStyle: UIAlertControllerStyle.Alert)

                        let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in
                            hostViewController.dismissViewControllerAnimated(true, completion: nil)
                        })
                        alertController.addAction(cancelAction)

                        hostViewController.presentViewController(alertController, animated: true, completion: nil)
                    })

                }


            }
            }


        task.resume()
        }
    }

我的请求网址:

https://www.udacity.com/api/users/Optional("3778758647")

我的ResponseKeys结构

struct JSONResponseKeys {
        //getSessionID
        static let Status = "status"
        static let Account = "account"
        static let Key = "key"
        static let Session = "session"
        static let ID = "id"

        //getUserData
        static let User = "user"
        static let FirstName = "first_name"
        static let LastName = "last_name"


    }

当我在下面的客户端中调用学生的名字和姓氏时,会发生解包可选值的致命错误:

UdacityClient.sharedInstance().firstName!) and      UdacityClient.sharedInstance().lastName!

JSON解析结果控制台日志

 {
    error = "Parameter 'user_key' key contains unescaped special character '\"': 'Optional(\"3778758647\")'";
    parameter = "user_key";
    status = 400;
}

2 个答案:

答案 0 :(得分:2)

我看起来你的主要错误来自userID是一个需要解包的可选值。这就是你看到

的原因

https://www.udacity.com/api/users/Optional("3778758647") 代替 https://www.udacity.com/api/users/3778758647并且您的服务器错误说明了同样的事情。

尝试这个基本大纲,而不是:

if self.userID == nil {
   ...
}

您可以使用保护声明提前返回,如下所示:

guard let userID = self.userID as? String else { return }

这样做的好处是还可以解开你的价值,摆脱"Optional()"

另一种方法是使用:

if let userID = self.userID as? String {
    ...
}

答案 1 :(得分:0)

首先,我建议你使用SwiftyJson进行数据解析(虽然我们可以使用Alamofire甚至afnetworking进行REST调用)。

我将举几个例子,用Swify解析数据有多简单。

这是对象的模型

public class MyObject: NSObject, JsonInitializableProtocol {
var name = ""
var value = ""
var count = 0

required public init(json:JSON) {
    name = json["Name"].stringValue ?? ""
    value = json["Value"].stringValue ?? ""
    count = json["Count"].intValue ?? 0
}

override init() {}
}

使用AFNetworking获取GET的NSData的函数,将其转换为JSON并创建MyObject类型的对象,并通过completionBlock传回它

func getObjWithUrl(url: String, completionHandler: (object: MyObject?, error: NSError?) -> Void) {
        manager.GET(url, parameters: nil, success: { (operation: AFHTTPRequestOperation!, data: AnyObject?) -> Void in
                let json = JSON(data : data as! NSData)
                let myObject = MyObject(json: json)
                completionHandler(myObject, nil)
            }, failure: { (operation: AFHTTPRequestOperation!, error: AnyObject?) -> Void in
                if let operationUnwrapped = operation as AFHTTPRequestOperation? {
                    var error = NSError(operation: operationUnwrapped, message: nil)
                    completionHandler(nil, wsError)
                }
            }
    }