我正在解析一个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