How to convert escaped JSON-string to NSString?
ios, json, objective-c
Solution
By default, Foundation will only parse JSON objects or arrays, but it can parse strings, numbers and booleans if you tell it to accept JSON fragments:
NSData *data = [@"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\""
dataUsingEncoding:NSUTF8StringEncoding];
id result = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:NULL];
NSLog(@"[result class] = %@", [result class]);
NSLog(@"result = %@", result);
Yields:
[result class] = __NSCFString
result = Some text.
Some text.
"Some text in quotes."
This is actually one of the cases where passing `error` really helps. I had tried without passing `NSJSONReadingAllowFragments` and got a very clear error message:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
Problem
I am working with a http-server, which return JSON-string in response body: ``` "Some text.\nSome text.\n\t\"Some text in quotes.\"" ``` I need remove quotes in the start and end of string, and I need unescape special symbols. I make category for NSString, but I think that it is wrong implementation: https://gist.github.com/virasio/59907e087f859e6c1723 I have other idea. I can use NSJSONSerialization: ``` NSString *sourceString = @"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\""; NSString *jsonObject = [NSString stringWithFormat:@"{ \"value\" : %@ }", sourceString]; NSDictionary *object = [NSJSONSerialization JSONObjectWithData:[jsonObject dataUsingEncoding:NSUTF8StringEncoding options:0 error:NULL]]; NSString *result = [object objectForKey:@"value"]; ``` But... It is not good too.