我对JSONSerialization.jsonObject有疑问(带有:dataResponse,选项:.allowFragments)

时间:2019-06-05 04:09:02

标签: json swift

  1. 我有一个关于
  2. 的问题
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"  }]

2 个答案:

答案 0 :(得分:0)

问题在于数据以JSON字符串明确的形式发送,并用双引号引起来,这是非常不常见的。

如果数据以双引号开头,则必须删除第一个和最后一个字节

let trimmedData : Data 
if dataResponse.first == 0x22 {
   trimmedData = dataResponse.dropFirst().dropLast()
} else {
   trimmedData = dataResponse
}
guard let jsonResponse = try JSONSerialization.jsonObject(with: trimmedData) as? [[String:Any]] else { return }
print("jsonResponse ==> \(jsonResponse)")

答案 1 :(得分:0)

好的,我想我知道“ JSON文本确实开始....”的原因。 由于在返回的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 "}]"

我该如何实现?