Objective-C: NSString is not fully decoded from UTF-8

I am requesting a web server that returns a JSON string as NSData. The string is in UTF-8 format, so it is converted to NSStringlike this.

NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 

However, some UTF-8 outputs remain in the output JSON string, which causes my application to behave erratically. Things like \u2019stay on the line. I tried everything to remove them and replace them with their actual characters.

The only thing I can think of is to replace UTF-8 events with screens with my characters manually, but this is a lot if there is a faster way!

Here is an example of an incorrectly parsed string:

{"title":"The Concept, Framed, The Enquiry, Delilah\u2019s Number 10  ","url":"http://livebrum.co.uk/2012/05/31/the-concept-framed-the-enquiry-delilah\u2019s-number-10","date_range":"31 May 2012","description":"","venue":{"title":"O2 Academy 3 ","url":"http://livebrum.co.uk/venues/o2-academy-3"}

As you can see, the URL has not been fully translated.

Thank,

+2
source share
1

\u2019 UTF-8, JSON- . NSString UTF-8, JSON, .

NSJSONSerialization JSON, .

, :

NSError *error = nil;
id rootObject = [NSJSONSerialization
                      JSONObjectWithData:receivedData
                      options:0
                      error:&error];

if(error)
{
    // error path here
}

// really you'd validate this properly, but this is just
// an example so I'm going to assume:
//
//    (1) the root object is a dictionary;
//    (2) it has a string in it named 'url'
//
// (technically this code will work not matter what the type
// of the url object as written, but if you carry forward assuming
// a string then you could be in trouble)

NSDictionary *rootDictionary = rootObject;
NSString *url = [rootDictionary objectForKey:@"url"];

NSLog(@"URL was: %@", url);
+7

All Articles