I am trying to parse a feed from a json webservice on my iPhone however the utf8 conversion is not working the way it should or am I doing something wrong Here is apart of
While sending to server
NSString* str1 = @"est un r \u00c3\u00aa ve en noir";
NSData *str1Data = [str1 dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *str2 = [[NSString alloc] initWithData:str1Data encoding:NSUTF8StringEncoding];
After receiving you can decode like this
NSData *recivedStrData = [recivedStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *strResult = [[NSString alloc] initWithData:recivedStrData encoding:NSNonLossyASCIIStringEncoding];
This works for me!
In iOS 9 don't need do anything. It is converted automatically.
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"response header: %@",response);
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response data: %@", aStr);
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *dict in json)
{
NSLog(@"%@", dict);
NSString *name = [dict objectForKey:@"name"];
NSString *msg = [dict objectForKey:@"message"];
NSString *topic = [dict objectForKey:@"topic"];
NSLog(@"*********** %@, %@, %@", name,topic,msg);
// now do something
}
After much grief I have figured this out. Use this.
NSString *correctString = [NSString stringWithCString:[utf8String cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
I think the test case is broken; the following:
NSString* str1 = @"est un r \u00c3\u00aa ve en noir";
NSLog(@"%@", str1);
Also outputs 'est un r ê ve en noir'. However, this:
NSString* str1 = @"est un rêve en noir";
NSLog(@"%@", str1);
Outputs 'est un rêve en noir', as does:
NSString* str1 = @"est un rêve en noir";
NSString* str = [NSString stringWithUTF8String:[str1 cStringUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", str);
And ditto for the slightly shorter version:
NSString* str1 = @"est un rêve en noir";
NSString* str = [NSString stringWithUTF8String:[str1 UTF8Encoding]];
NSLog(@"%@", str);
And, indeed:
char *str1 = "est un r\xc3\xaave en noir";
NSString* str = [NSString stringWithUTF8String:str1];
NSLog(@"%@", str);
I think it's a question of JSON, not UTF8. The \u followed by four hexadecimal digits is JSON's way of encoding a generic UTF16 character, it's not an inherent part of UTF. So NSString doesn't know how to deal with it. Your JSON parser needs to be adapted to parse escape sequences properly.