繁体   English   中英

如何在 Swift 中解析 JSON 数组?

[英]How to parse a array of JSON in Swift?

我是 Swift 的初学者。 我尝试在 Swift 中发出 http 请求。

我成功地做到了,但我无法解析响应。 我对此进行了很多搜索,但找不到任何东西。

这是我的一段代码。

上面代码的输出是:

{

  Login =     {

        AccountType = Pro;
        FileSizeLimit = 157286400;
        PasswordHash = fc27a61bc3dda36ebe28887d4da16df2093bbbcd8d58cfc87b2b48b70801c411;

        Session =         {
            id = ca77dd997db2169908a1a84204c99ae7;
        };

        SmugVault = 0;

        User =         {
            DisplayName = "smug";
            NickName = better1;
            id = 2455641;
        };

    };
    method = "smugmug.login.withPassword";
    stat = ok;

}

我想获取显示名称。 我能够提取 sessionId 但不能提取名称。 请帮我解决一下这个。

波纹管是代码

func postDataToURL() {

    let userName = self.userName.text;
    let userPassword = self.password.text;

    let postUrl = NSURL(string: "http://api.smugmug.com/hack/json/1.2.0/?method=smugmug.login.withPassword")!

    let smugUrlRequest = NSMutableURLRequest(URL: postUrl)

    smugUrlRequest.HTTPMethod = "POST"

    let postString = "&EmailAddress=" + userName! + "&Password=" + userPassword! + "&APIKey=1WcKTxQH2fegQTF0C7cVAORjeoTSD68V"

    smugUrlRequest.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(smugUrlRequest) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            print("ERROR")
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                if let stat = json["method"] as? String {
                    print(stat) // London
                }

                print(json)

                let user = json["Login"]!
                let FileSizeLimit = user["FileSizeLimit"]
                print(FileSizeLimit)

                let PasswordHash = user["PasswordHash"]
                print(PasswordHash)

                let Session = user["Session"]
                print(Session)

                let DisplayName = user["User"]
                print(DisplayName)


            }
        } catch let error as NSError{
            print("\(error)")
        }


    }
    task.resume()
}

问题解决了。 解决方案是

   let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            do {
                let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                print("jsonResult : ",jsonResult)
                print("Session : ",jsonResult.valueForKey("Login")?.valueForKey("Session"))
                print("DisplayName : ",(jsonResult.valueForKey("Login")?.valueForKey("User")?.valueForKey("DisplayName"))!)

            } catch {

}

暂无
暂无

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

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