I have JSON method and work nice on UTF8 webservices, but now have a JSON with another encoding, for example ú = \u00da. I know I have to encoding to UTF8 to work my JSON on swift. But I don't know how. On request.HTTPBody have a .dataUsingEncoding, it is not enough?
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
let jsonEmpresas = myJSON["TablaEmp"]!!["item"]
let empresas: [[String: AnyObject]]
if let multipleEmpresas = jsonEmpresas as? [[String: AnyObject]] {
empresas = multipleEmpresas
} else if let singleEmpresa = jsonEmpresas as? [String: AnyObject] {
empresas = [singleEmpresa]
} else {
empresas = []
}
for empresa in empresas{
let zcif = empresa["Zcif"] as? String
I had let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) before Do, but was not used
ERROR: "Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.} "
If you want to send emoji or other Unicode character as a parameter You need to encode the HTTP request like postString.dataUsingEncoding(NSUTF8StringEncoding)!. But as you told on comments this web service will send only Strings or Int So It's okay to use postString.dataUsingEncoding(NSASCIIStringEncoding)!. Because that line affect for only sending parameter, it's encoding sending parameters only not decode the receiving JSON values.So basically just take the JSON value.
So basically when you return a encoded value apple support to those encode text
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error:
So according to apple and my experience I think Your server DB send the data by using apple unsupported encode option. As I told before, Your Server DB should use UTF-8.Your DB tables using another encoding options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With