[ NSJSONSerialization, NSURLSession, Unicode in application/json responses ]
I am using NSURLSession to communicate with web servers, and NSJSONSerialization to decode JSON. I am having trouble interpretting emoji characters.
For example, I have a JSON file at: https://www.virtualsanity.com/unicode.json
The content of the file is:
{"\uf4a9": "\uf4a9"}
The key and value in the dictionary is "\uf4a9". I believe that is a properly-escaped ������ character.
I have this Swift code running on iOS 9:
let urlSession = NSURLSession.sharedSession()
let url = NSURL(string: "https://www.virtualsanity.com/unicode.json")!
let request = NSMutableURLRequest(URL: url)
let dataTask = urlSession.dataTaskWithRequest(request) { (data, urlResponse, error) in
print("encoding: ", urlResponse?.textEncodingName)
if let responseData = data {
if let json = try? NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions()) {
if let dictionary = json as? [String: String] {
for (key, value) in dictionary {
print("key: \(key), value: \(value)")
}
}
} else {
print("Unable to deserialize json")
}
} else {
print("No response data")
}
}
dataTask.resume()
I expect both the key and value of the resulting dictionary to be a ������ character. Instead they are garbage characters.
I am hoping someone can help me understand what I am doing wrong.
Answer 1
Actually the unicode for ������ is \u1F4A9
, try this in a playground:
print("\u{1f4a9}")
print("\u{f4a9}")