我正在尝试从后端提取一个JSON文件,其中包含用于表情符号的独角兽。这些不是遗留的独角兽(例如:\ the 415),而是跨平台工作的独角兽(例如:\U0001F604)。
下面是json被拉出来的一个样本:
[
{
"unicode": "U0001F601",
"meaning": "Argh!"
},
{
"unicode": "U0001F602",
"meaning": "Laughing so hard"
}
]我很难将这些字符串转换成独角兽,它将在应用程序中显示为表情符号。
任何帮助都是非常感谢的!
发布于 2014-07-09 23:08:33
为了将这些unicode字符转换为NSString,您需要获取这些unicode字符的字节。
获得字节后,很容易用字节初始化NSString。下面的代码完全符合您的要求。它假设jsonArray是从您的json被拉出来的NSArray。
// initialize using json serialization (possibly NSJSONSerialization)
NSArray *jsonArray;
[jsonArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *charCode = obj[@"unicode"];
// remove prefix 'U'
charCode = [charCode substringFromIndex:1];
unsigned unicodeInt = 0;
//convert unicode character to int
[[NSScanner scannerWithString:charCode] scanHexInt:&unicodeInt];
//convert this integer to a char array (bytes)
char chars[4];
int len = 4;
chars[0] = (unicodeInt >> 24) & (1 << 24) - 1;
chars[1] = (unicodeInt >> 16) & (1 << 16) - 1;
chars[2] = (unicodeInt >> 8) & (1 << 8) - 1;
chars[3] = unicodeInt & (1 << 8) - 1;
NSString *unicodeString = [[NSString alloc] initWithBytes:chars
length:len
encoding:NSUTF32StringEncoding];
NSLog(@"%@ - %@", obj[@"meaning"], unicodeString);
}];https://stackoverflow.com/questions/24662336
复制相似问题