Convert UTF-8

Hi guys, I grab the JSON array and save it in NSArray, however it includes UTF-8 JSON encoded strings, for example pass \ u00e9 represents passé. I need a way to convert all of these different types of strings to an actual character. I have a complete NSArray for conversion. Or I can convert it when it is displayed, which has ever been the easiest.

I found this diagram http://tntluoma.com/sidebars/codes/

Is there a convenience method for this or a library that I can download?

thanks,

By the way, I can’t find to change the server, so I can only fix it at my end ...

+4
source share
2 answers

You can use an approach based on NSScanner . The following code (without errors) can give you a way to work:

NSString *source = [NSString stringWithString:@"Le pass\\u00e9 compos\\u00e9 a \\u00e9t\\u00e9 d\\u00e9compos\\u00e9."]; NSLog(@"source=%@", source); NSMutableString *result = [[NSMutableString alloc] init]; NSScanner *scanner = [NSScanner scannerWithString:source]; [scanner setCharactersToBeSkipped:nil]; while (![scanner isAtEnd]) { NSString *chunk; // Scan up to the Unicode marker [scanner scanUpToString:@"\\u" intoString:&chunk]; // Append the chunk read [result appendString:chunk]; // Skip the Unicode marker if ([scanner scanString:@"\\u" intoString:nil]) { // Read the Unicode value (assume they are hexa and four) unsigned int value; NSRange range = NSMakeRange([scanner scanLocation], 4); NSString *code = [source substringWithRange:range]; [[NSScanner scannerWithString:code] scanHexInt:&value]; unichar c = (unichar) value; // Append the character [result appendFormat:@"%C", c]; // Move the scanner past the Unicode value [scanner scanString:code intoString:nil]; } } NSLog(@"result=%@", result); 
+1
source

If you use the JSON Framework , then all you do is get the JSON string and convert it to NSArray as follows:

 NSString * aJSONString = ...; NSArray * array = [aJSONString JSONValue]; 

The library is well written and automatically processes UTF8 encoding, so you do not need to do anything outside of it. I used this library several times in in-store applications. I highly recommend using this approach.

+1
source

Source: https://habr.com/ru/post/1307984/


All Articles