Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly Handle UTF-8 In JSON on iOS

I'm receiving some JSON that has weird UTF-8 strings. Eg:

{
  "title": "It\U2019s The End";
}

What's the best way to handle this data so that it can be presented in a readable way? I'd like to convert that \U2019 into the quote mark that it should represent.

Edit: Assume I have parsed the string into a NSString* jsonResult

Edit 2: I'm receiving the JSON through AFNetworking:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSString* jsonResult = [JSON valueForKeyPath:@"title"];
} failure:nil];
like image 617
hodgesmr Avatar asked Oct 05 '22 03:10

hodgesmr


1 Answers

Update:

Kurt has brought to attention that AFJSONRequestOperation uses NSJSONSerialization under the hood. As such, it's probably the case that your JSON is invalid (as mentioned below, there shouldn't be a ;, and the U should be a lowercase u. This was mentioned in the original answer below.


It's part of the way JSON is able to store its data. You will need to pass your JSON string through a JSON parser, then you will be able to extract your string correctly.

Note: The JSON you've posted above is invalid, there shouldn't be a semi-colon at the end, and the U should be a lower-case u; the example below has a modified JSON string

NSString* str = @"{\"title\": \"It\\u2019s The End\"}";

NSError *error = nil;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                               options:0
                                                                 error:&error];
if (error) {
    // Handle an error in the parsing
}
else {
    NSString *title = [rootDictionary objectForKey:@"title"];
    NSLog(@"%@", title); //Prints "It’s The End"
}
like image 179
WDUK Avatar answered Oct 10 '22 10:10

WDUK