How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)
It looks like you are passing an NSString
parameter where you should be passing an NSData
parameter:
NSError *jsonError;NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
For example you have a NSString
with special characters in NSString
strChangetoJSON.Then you can convert that string to JSON response using above code.
I've made a category from @Abizern answer
@implementation NSString (Extensions)- (NSDictionary *) json_StringToDictionary { NSError *error; NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error]; return (!json ? nil : json);}@end
Use it like this,
NSString *jsonString = @"{\"2\":\"3\"}";NSLog(@"%@",[jsonString json_StringToDictionary]);