Reputation: 25745
I need to send a message to the server which contains emojis. I read the data from CoreData, store it in dictionary and then convert it into json format.
My initial dictionary has following content
["0": ["chat_token": "8g9nu0Z.a3", "message": "🤛👌", "user_id": "1242", "created": "2017-12-29 17:13:16"]]
I then convert it into JSON using following code
do {
let jsonData = try JSONSerialization.data(withJSONObject: resultDict, options: [])
if let jsonText = NSString(data: jsonData, encoding: String.Encoding.ascii.rawValue) {
return jsonText as String
}
} catch let error {
print(error)
}
This returns me following json string
{"0":{"chat_token":"8g9nu0Z.a3","message":"ð¤ð","user_id":"34","created":"2017-12-29 17:13:16"}}
The problem is emojis are not correctly formatted. In JSON it gets converted to ð¤ð
The reason I need it is to send it to the server to store the message. How do I convert emoji to json string format.
Upvotes: 2
Views: 5918
Reputation: 54706
The issue is that you are trying to initialize the String
with ASCII encoding, in which emojis doesn't exist. You should be using UTF-8.
You also shouldn't be using NSString
, since you are returning a String
anyways and aren't using any NSString
specific functionality.
do {
let jsonData = try JSONSerialization.data(withJSONObject: resultDict)
if let jsonText = String(data: jsonData, encoding: .utf8) {
return jsonText
}
} catch let error {
print(error)
}
Output:
"{"0":{"chat_token":"8g9nu0Z.a3","message":"🤛👌","user_id":"1242","created":"2017-12-29 17:13:16"}}"
Upvotes: 4