Search code examples
objective-cjsonnsjsonserialization

Replacing stuff in JSON string


Why do I get an error with this:

NSString *jsonString = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"jsonRoster unmasked: %@", jsonString);
NSString *maskedString = [self maskJSON:jsonString withMultipleElementStartString:@"###multipleElementsBegin###" andMultipleEndString:@"###multipleElementsEnd###" andSingleElementStartString:@"###elementBegin###" andSingleElementEndString:@"###elementEnd###"];
NSLog(@"jsonRoster masked: %@", maskedString);

Here is the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x600002932400'

But why, is the string still a Dictionary?


Solution

  • As per error message JSONObjectWithData returned an NSDictionary object, in fact it is in practice so, JSONObjectWithData returns a dictionary or an array depending on your JSON structure. So you should normally check return type and handle it properly.

    Edit To get an NSString you can use its initWithData:encoding: method.