1

I have tried to search in Stackoverflow. But I could not get the correct solution. Can someone please help me?

I have this data from a web service.

KEY: 1036   TYPE: string    VALUE = French (fran\u00E7aise)
KEY: 1032   TYPE: string    VALUE = Greek  (\u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC)

Does anyone know how to print this Unicode string correctly? I have tried to encode and decode it back (as shown below). But it is not working. :(

NSString *value = [NSString stringWithFormat:@"%@", t.dataValue]; 
NSData *bytes = [message dataUsingEncoding:NSUTF8StringEncoding];
NSString* messageDecoded = [[NSString alloc] initWithData:bytes encoding:NSUTF8StringEncoding];
NSLog(@"decoded: %@", messageDecoded);

Thanks in advance guys!

ANSWER:

I got an answer from this link:

NSString* input = @"ab\"cA\"BC\\u2345\\u0123";
// will cause trouble if you have "abc\\\\uvw"
NSString* esc1 = [input stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
NSString* esc2 = [esc1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString* quoted = [[@"\"" stringByAppendingString:esc2] stringByAppendingString:@"\""];
NSData* data = [quoted dataUsingEncoding:NSUTF8StringEncoding];
NSString* unesc = [NSPropertyListSerialization propertyListFromData:data
  mutabilityOption:NSPropertyListImmutable format:NULL
  errorDescription:NULL];
assert([unesc isKindOfClass:[NSString class]]);
NSLog(@"Output = %@", unesc);
Community
  • 1
  • 1
Kiki Chandra
  • 187
  • 1
  • 15
  • 1
    It's because that's not UTF-8. It's ASCII or ISO-Latin-1 or some such with escaped unicode characters. If you can get your web service to actuallly send you a UTF-8 encoded string, that'd be ideal. If not, you'll have to iterate over the returned string and unescape the characters. – Jason Coco Jul 06 '12 at 15:50
  • Hey Jason, what do you mean by unescape the characters? What I am confused is that if I do "NSLog(@"fran\u00E7aise")", it prints the correct string ! :( – Kiki Chandra Jul 06 '12 at 15:53
  • It prints that because the compiler unescaped the characters for you and converted the string to UTF-8 before writing it to your apps static data section. – Jason Coco Jul 06 '12 at 15:55
  • Thanks.. It is starting to get clear now ! – Kiki Chandra Jul 06 '12 at 16:18

0 Answers0