简体   繁体   中英

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];

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM