Emoji characters cannot be encoded to JSON Emoji characters cannot be encoded to JSON json json

Emoji characters cannot be encoded to JSON


I use the below code to encode emoji character

NSString *uniText = [NSString stringWithUTF8String:[textview.text UTF8String]]; NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding]; NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding] ;

And the below code to decode and display in UILabel

const char *jsonString = [body UTF8String]; NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)]; NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];


Edit - 2016-03-03 Please note, this answer was written in 2011 and may no longer be relevant any more.

Emoji characters are just a specific font used to render specific unicode code points. iOS uses one of the Unicode Private Use Areas for Emoji-specific code points. The only way to view these "characters" as Emoji is to have an Emoji font available as well as a machine that knows how to switch from the default text font (such as Helvetica) to the emoji font.

I don't know how you're encoding your JSON but since Emoji are just text there shouldn't be any problems as long as you transport the text in a Unicode-friendly format such as UTF-8 or UTF-16. You won't see it on the server-side or in the database (unless you view the data with the previous prerequisites) but you should be able to send the same raw bytes back and it should look the same.

Here's some posts that might help a little more:


I had the same problem, after digging for hours and finally found this answer that works for me:https://stackoverflow.com/a/8339255/1090945

If you are using rails as your server, this is all you need to do. No need to do anything in ios/xcode, just pass the NSString without doing any UTF8/16 encoding stuff to the server.

Postegre stores the code correctly, it's just when you send the json response back to your ios client, assuming you do render json:@message, the json encoding has problem.

you could test whether you are having json encoding problem in your rails console by doing as simple test:

test = {"smiley"=>"u{1f604}"} test.to_json

if it prints out "{\"smiley\":\"\uf604\"}" (notice the 1 is lost), then you have this problem. and the patch from the link will fix it.