简体   繁体   English

使用swift解析json数据时出错“数据无法读取,因为格式不正确。”

[英]error when parsing json data with swift “The data couldn’t be read because it isn’t in the correct format.”

anyone who knows about retrieving data from a database and using it to check if a user exits (sign in) please help. 任何知道从数据库中检索数据并使用它来检查用户是否退出(登录)的人都请帮忙。 My head is wrecked and unfortunately my coding is not quite good enough to fix the problem! 我的头被破坏了,不幸的是我的编码不足以解决问题!

 do {


                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
                {


                    let parseJSON = json

                    let userID = parseJSON["userId"] as? String //dictionary object that uses a key

                    if(userID != nil)
                    {
                        //everything is fine and take user to main page 
                        //instantiate the view controller
                        let profilePage = self.storyboard?.instantiateViewControllerWithIdentifier("ProfilePageViewController") as! ProfilePageViewController

                        //wrap it in nav controller

                        let profilePageNav = UINavigationController(rootViewController: profilePage)

                        //take user to this page
                        //window root view controller- existing is replaced and no back button

                        let appDelegate = UIApplication.sharedApplication().delegate
                        appDelegate?.window??.rootViewController = profilePageNav




                    }else{
                        //display the alert message from the php file
                        let errorMessage = parseJSON["message"] as? String


                        let myAlert = UIAlertController(
                            title: "Alert!",
                            message: errorMessage,
                            preferredStyle: UIAlertControllerStyle.Alert)

                        //create a button action -
                        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)

                        //adding ok button and presenting to a user and once ok button is pressed- dismiss the view
                        myAlert.addAction(okAction)
                        self.presentViewController(myAlert, animated: true, completion:nil)





                    }


                }//end of if let json
            }//end of do
            catch let error as NSError {
                print(error.localizedDescription)
            }



            print("success")

        }//end of dispatch_async
    }).resume()//end of request




}//end of action sign in

I think the issue is with the if let json = try line, the data is not in the correct format. 我认为问题在于if let json = try行,数据格式不正确。 My php script is working well and I can pass parameters in the browser and all seems ok. 我的PHP脚本运行良好,我可以在浏览器中传递参数,一切似乎都可以。 The key is correct (userId). 密钥是正确的(userId)。 I think another issue is with let userID = parseJSON["userId"] as? 我认为另一个问题是让userID = parseJSON [“userId”]为? String

if I have made a request for the data as an NSDictionary - how can I convert this info to type String (I'm sure you can't anyways) Sorry - a lot of questions. 如果我作为NSDictionary请求数据 - 如何将此信息转换为String类型(我相信你不能反正)抱歉 - 很多问题。 I need String representations to use in another view controller. 我需要在另一个视图控制器中使用String表示。 I have been trying this for ages and I can't get it to work so I would really appreciate some help- When i run the code- it bypasses the "do" block and goes straight to the .localizedDescription 我已经尝试了很多年,我无法让它工作,所以我真的很感激一些帮助 - 当我运行代码时 - 它绕过“do”块并直接进入.localizedDescription

Thank you for talking the time to read my v long question! 感谢您抽出时间阅读我的v问题!

The issue is definitely in NSJSONSerialization.JSONObjectWithData which doesn't like your JSON for some reason. 问题肯定出在NSJSONSerialization.JSONObjectWithData中,由于某些原因它不喜欢你的JSON。

Try cleaning your JSON before feeding it to NSJSONSerialization: 尝试清理JSON,然后再将其提供给NSJSONSerialization:

var dataString = String(data: data, encoding: NSUTF8StringEncoding)!
dataString = dataString.stringByReplacingOccurrencesOfString("\\'", withString: "'")
let cleanData: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)!

发送请求时“request.setValue(”application / json“,forHTTPHeaderField:”Accept“)”解决了我的错误。

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

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