If you’re like me, a long time .NET developer that finally also became iOS Developer, most likely you’ll use .NET to create server-side API/backend to serve iOS apps. If yes, you may use OData or WCF Data Services to implement such backend. Long before ASP.NET Web API came along, OData is the easiest way to create API.
OData can output JSON, even though it outputs in XML by default. As we know, we simply add/change “Accept” header in our HTTP request to “application/json” to get JSON responses. iOS SDK has built-in JSON parsing support since iOS 5 by using NSJSONSerialization class. All seems a perfect combination, while occasionally it’s not.
The problem with OData is that it returns JSON string a little bit different than another technologies. If there’s a string data that contains single quote (‘) or apostrophe, it will escape it. So if you have a string like this to return:
1 |
a five-star resort for the world's monsters |
OData will automatically escape the quote to:
1 |
a five-star resort for the world\'s monsters |
And nothing I can do about it, nothing that I know. If you know, please please let me know 🙂
So, what should we do? We have to do a little bit more effort in client-side, in this case when using NSJSONSerialization.
Let’s say you get the NSData from HTTP response, all you have to do is:
1 2 3 4 5 6 7 8 9 |
//data is the returned NSData object from HTTP response NSString *_str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSString *_escapedString = [_str stringByReplacingOccurrencesOfString:@"\\'" withString:@"'"]; [_str release]; NSData *_escData = [_escapedString dataUsingEncoding:NSUTF8StringEncoding]; id obj = [NSJSONSerialization JSONObjectWithData:_escData options:0 error:nil]; //obj is the parsed data |
That’s it. Enjoy!