Reputation: 39
I am grabbing a JSON array and storing it in an 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 convenient 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...
Upvotes: 3
Views: 965
Reputation: 243146
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.
Upvotes: 1
Reputation: 27889
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);
Upvotes: 1