首页 > 解决方案 > 我对 JSONSerialization.jsonObject(with: dataResponse, options: .allowFragments) 有一些疑问

问题描述

  1. 我有一个问题
let jsonResponse = try JSONSerialization.jsonObject (with: dataResponse, options: .allowFragments)
print ("jsonResponse ==> (jsonResponse)")

我想更改值 jsonResponse ==> jsonArray 但该值未发送到 jsonArray jsonArray ==> jsonDictionary

然后使用 JSON 字典检查登录...

  1. 我有更多错误
guard let jsonDictionary: Dictionary = jsonArray [0] else {==> Have warning = Non-optional expression of type '[String: Any]' used in a check for optionals
   return
} // guard
print ("jsonDictionary ==> (jsonDictionary)")

如果我改变

- JSONSerialization.jsonObject (with: dataResponse, options: [])

出现错误“JSON 文本未以数组或对象开头,并且允许未设置片段的选项。”

//  function check Authen
    func checkAuthen(truckNo: String, pass: String, imei: String) -> Void {
        let myconstant = Myconstant()
        let urlcheckLogin = myconstant.jsonGetDataCheckAuthen(pTruckNo: truckNo, pPassword: pass, pIMEI: imei)
        print("urlcheckLogin ==> \(urlcheckLogin)")

        guard let url = URL(string: urlcheckLogin) else {
            return
        }//Guard

//      task
        let task = URLSession.shared.dataTask(with: url){ (data, response, error) in
            guard let dataResponse = data, error == nil else{
                print("Have Error")
                return
            }//guard

            do{
//             read json from API
                let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: .allowFragments)
                print("jsonResponse ==> \(jsonResponse)")

//              change json to array
                guard let jsonArray = jsonResponse as? [[String:Any]] else{
                    return
                }//guard
                print("jsonArray ==> \(jsonArray)")

                guard let jsonDictionary: Dictionary = jsonArray[0] else{
                    return
                }//guard
                print("jsonDictionary ==>\(jsonDictionary)")

//              check  true password for json dictionary
                let truePassword: String = jsonDictionary["Password"] as! String
                print("truePassword ==>\(truePassword)")

                if pass == truePassword{
//                 password incorrect
                    DispatchQueue.main.async {
                        self.performSegue(withIdentifier: "GotoPlanData", sender: self)
                    }//DispatchQueue
                }else{
//                  password incorrect
                    self.showAlert(title: "Password incorrect", message: "Plase try again")
                }//if
            }catch let myerror{
                print(myerror)
//              check display username in database
                print("No have user \(truckNo) in database")
                DispatchQueue.main.async {
                    self.showAlert(title: "No username", message: "No have user \(truckNo) in database")
                }//DispatchQueue
            }//catch
        }//task
        task.resume()
    }//checkAuthen

结果

No Space
urlcheckLogin ==> http://www.testservice.com/Service/CheckUserLogin/60-7625/1234/355750067867310
username ==> Optional("60-7625")
password ==> Optional("1234")
jsonResponse ==> [{ "Result": "Valid",    "TruckNo": "60-7625",    "TruckID": "10"  }]

标签: jsonswift

解决方案


好的,我想我知道“JSON text did to start ....”的原因是由于在返回的dataResponse中有一个标记\,导致无法读取jsonResponse值

Example:
dataResponse ==> "[  {    \"Result\": \"Valid\",    \"TruckNo\": \"60-7625\",    \"TruckID\": \"10\"  }]"

我想切记。我应该如何编写代码?

正在寻找替换 Swift String 中的字符。

Example :  
dataResponse ==> "[  {    \"Result\": \"Valid\",    \"TruckNo\": \"60-7625\",    \"TruckID\": \"10\"  }]"

我想用“”替换如何获得:

Example:
dataResponse ==> "[{" Result ":" Valid "," TruckNo ":" 60-7625 "," TruckID ":" 10 "}]"

我怎样才能做到这一点?


推荐阅读