NSJSONSerialization and Emoji

后端 未结 2 1480
抹茶落季
抹茶落季 2020-12-19 21:48

I\'m currently trying to POST some JSON containing emojis to a python API. I tried feeding the NSJSONSerialization directly with the string containing the emojis fr

相关标签:
2条回答
  • 2020-12-19 22:16

    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 = @"                                                                    
    0 讨论(0)
  • 2020-12-19 22:24

    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".

    0 讨论(0)
提交回复
热议问题