views:

225

answers:

2
+3  Q: 

UTF-8 conversion

Hey guys, I am grabbing a JSON array and storing it in a NSArray, however it includes JSON encoded UTF-8 strings, for example pass\u00e9 represents passé. I need a way of converting all of these different types of strings into the actual character. I have an entire NSArray to convert. Or I can convert it when it is being displayed, which ever is easiest.

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

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

thanks,

BTW, there is no way I can find to change the server so I can only fix it on my end...

+1  A: 

You can use an approach based on the NSScanner. The following code (not bug-proof) can gives you a way on how it can 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);
Laurent Etiemble
Looks promising, but I do not see how it will convert every type character, for example "in the cell's nucleus"
leachianus
+1  A: 

If you use the JSON Framework, then all you do is get your JSON string and convert it to an NSArray like so:

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

The library is well-written, and will automatically handle UTF8 encoding, so you don't need to do anything beyond this. I've used this library several times in apps that are on the store. I highly recommend using this approach.

Dave DeLong
I am already doing this: NSURL *url = [NSURL URLWithString:string]; NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url]; NSDictionary *dict = [jsonreturn JSONValue];
leachianus