NSJSONSerialization and Emoji

百般思念 提交于 2019-11-29 11:53:27

There are two difficulties:
1. Apple hosed NSString WRT UTF Planes 1 and above, the underlying use of UTF-16 shows through. An example is that length will return 2 for one emoji character.
2. Whoever decided to put emoji in Plane 1 was just being difficult, it is the first use of Plane 1 and a lot of legacy UTF code does not handle that correctly.

Example code (adapted from @Hot Licks): Updated with OP emoji

NSString *uniText = @"💦💏👒👒💦";
NSDictionary* jsonDict = @{@"title":uniText};

NSData * utf32Data = [uniText dataUsingEncoding:NSUTF32LittleEndianStringEncoding];
NSLog(@"utf32Data: %@", utf32Data);

NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
if (jsonData == nil) {
    NSLog(@"JSON serialization error: %@", error);
}
else {
    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"The JSON result is %@", jsonString);
    NSLog(@"jsonData: %@", jsonData);
}

NSLog output

utf32Data: a6f40100 8ff40100 52f40100 52f40100 a6f40100
The JSON result is {"title":"💦💏👒👒💦"}
jsonData: 7b227469 746c6522 3a22f09f 92a6f09f 928ff09f 9192f09f 9192f09f 92a6227d

Sigh:

NSString* uniText = mytextField.text;
NSDictionary* jsonDict = @{@"title":uniText};
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJsonObject:jsonDict options:0 error:&error];
if (jsonData == nil) {
    NSLog(@"JSON serialization error: %@", error);
}
else {
    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"The JSON result is %@", jsonString);
}

If myTextField.text is a valid NSString then no other conversions should be required. NSJSONSerialization will provide all necessary "escaping".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!