I have the following JSON String:
{"success":1,"data":{"address":"Ny Kærvej 20, 9100 Aalborg, Denmark","email":"adm1@fjerkraeservice.dk","username":"DFSADM","phonenumber":"61366932","status":"0","id":"2011"}}
It was retrieved using loadDataTask via a NSURLSession as a block of data.
The following code is used to parse it after:
var json: [String: AnyObject]!
do {
self.appDelegate.printJSONResponse(data, message: "\(#function)")
json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String: AnyObject]
} catch {
// alwyas fails to here when non ascii unicode present
print(error)
}
// Work around
if (json == nil) {
do {
if let serverStr = String.init(data: data, encoding: NSASCIIStringEncoding) {
let asciiData = serverStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
json = try NSJSONSerialization.JSONObjectWithData(asciiData!, options: NSJSONReadingOptions()) as? [String: AnyObject]
}
} catch {
print(error)
}
}
The line
json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String: AnyObject]
always fails if there embedded non pure ascii characters. Error message is :
Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 31." UserInfo={NSDebugDescription=Unable to convert data to string around character 31.}
The balance of the cod provides a work around but obviously loses some data.
What's going on?