JSON Array не анализируется и не получает код ошибки из-за специальных символов и как их игнорировать? - PullRequest
0 голосов
/ 21 июня 2019

Я анализирую массив json и получаю правильные данные, но если массив json содержит какие-либо специальные символы, такие как & и т.д., он получает код ошибки. Я поделюсь с вами своим кодом, пожалуйста, проверьте и помогите мне. Спасибо

// Синтаксический анализ XML

let LocationMessage = "<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://tempuri.org/'><SOAP-ENV:Body><ns1:GetBROMCoordinateByLatLogRad><ns1:latitude>\(place.coordinate.latitude)</ns1:latitude><ns1:logitude>\(place.coordinate.longitude)</ns1:logitude><ns1:radius>200</ns1:radius></ns1:GetBROMCoordinateByLatLogRad></SOAP-ENV:Body></SOAP-ENV:Envelope>"


let LocationurlString = "http://104.xxx./xyzapiservice/API/xyzService.svc"

let LocationmsgLength = String(LocationMessage.count)
let LocationUrl = NSURL(string: LocationurlString)!

var LocationRequest = URLRequest(url: LocationUrl as URL)
LocationRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type")
LocationRequest.addValue("http://tempuri.org/xyxApiService/GetBROMCoordinateByLatLogRad", forHTTPHeaderField: "Soapaction")
LocationRequest.addValue(LocationmsgLength, forHTTPHeaderField: "Content-Length")

LocationRequest.httpMethod = "POST"
LocationRequest.httpBody = LocationMessage.data(using: .utf8)

let Locationsession = URLSession.shared
let Locationtask = Locationsession.dataTask(with: LocationRequest as URLRequest) { (data, response, error) in
    guard let Locationresponse = data,
        error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return }

    print("Track Response: \(String(describing: response))")

    let Locationparser = XMLParser(data: Locationresponse)
    Locationparser.delegate = self
    Locationparser.parse()
}
Locationtask.resume()

 func parser(_ parser: XMLParser, foundCharacters string: String) {

        if (!string.isEmpty) {
            if currentParsingElement == "GetBROMCoordinateByLatLogRadResult" {
                getLocation = string
                print("Location is",getLocation)

                let jsonData = getLocation.data(using: .utf8)


                do{
                    let jsonResponse = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
                    print("JSON Data is", jsonResponse) //Response result

                    guard let jsonArray = jsonResponse as? [[String: Any]]
                        else {
                            return
                    }
                        print("JSON Array is", jsonArray)

Ошибка консоли:

"BranchType":"Pejabat POS","BranchName":"Pejabat POS Pengkalan Weld","BranchCode":"1052","BranchAddress1":"Unit 1.22 
Error Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.}
Location is &
Error Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
Location is  1.23,","BranchAddress2":"Blok U-Shaped 111, Leboh Gat Maccallum,","BranchAddress3":"","Postcode":"10300","City":"Pulau Pinang","Latitude":"5.406208","Longitude":"10
...