1

i am building an application that imports JSON results and parses the objects to a table cell. Nothing fancy, but in my results, many of the terms/names are European with characters such as è or ú which come out as \u00E9 or \u00FA. I think these are ASCII ? or unicode? ( i can never keep em staight). Anyway, like all good NSSTring's, i figured there must be a method to fix this, but i am not finding it....any ideas? I am trying to avoid doing something like this: this posting. Thanks all.

Community
  • 1
  • 1
mlecho
  • 1,149
  • 2
  • 10
  • 14
  • 1
    Unicode. If it helps you to remember, look at the "u" in the escape code. Also, ASCII is only 0-127 so 0xFA is already outside ASCII. – u0b34a0f6ae Sep 06 '09 at 13:41
  • Rather than de-escaping the string yourself, having you considered using an existing Objective-C based JSON library which will handle this kind of thing for you behind a clean API? The first hit from google for example - http://code.google.com/p/json-framework/ would allow you to do something like the following NSDictionary * dict = [myStringContainingJSONData JSONValue]; and your main application source wouldn't need to concern itself with parsing or encoding type issues. – Christopher Fairbairn Oct 21 '09 at 22:54
  • thanks christopher, i am using this framework, but it's not the answer – mlecho Jan 21 '10 at 23:55

2 Answers2

1

As kaizer.se pointed out, these are unicode characters. And the NSString method you might be able to use is +stringWithContentsOfURL. or +stringWithContentsOfFile. For example:

NSError *error;
NSString *incoming = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://sender.org"] encoding:NSUnicodeStringEncoding error:&error];
Elise van Looij
  • 4,162
  • 3
  • 29
  • 52
0

So you're talking about unicode escape sequences. They're just character codes, and can be converted using printf-style '%C'.

NSScanner would probably be a good way to do this... here's a crack at it (ew):

NSString* my_json = @"{\"key\": \"value with \\u03b2\"}";
NSMutableString* clean_json = [NSMutableString string];
NSScanner* scanner = [NSScanner scannerWithString: my_json];
NSString* buf = nil;
while ( ! [scanner isAtEnd] ) {
    if ( ! [scanner scanUpToString: @"\\u" intoString: &buf] )
        break;//no more characters to scan
    [clean_json appendString: buf];
    if ( [scanner isAtEnd] )
        break;//reached end with this scan
    [scanner setScanLocation: [scanner scanLocation] + 2];//skip the '\\u'
    unsigned c;
    if ( [scanner scanHexInt: c] )
        [clean_json appendFormat: @"%C", c];
    else
        [clean_json appendString: @"\\u"];//nm
}
// 'clean_json' is now a string with unicode escape sequences 'fixed'
GoldenBoy
  • 1,381
  • 1
  • 8
  • 11