Search code examples
iphoneobjective-cjsonsbjson

Getting error when trying to set value/key pairs with SBJsonWriter


Getting the following error when trying to set value/key pairs:

2011-06-21 16:21:16.727 agent[94408:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<SBJsonWriter 0xab31230> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key key.'

Here is the code:

SBJsonWriter *writer = [[SBJsonWriter alloc] init];

[writer setValue:@"val" forKey:@"key"];

NSString *json = [writer JSONRepresentation];

NSLog([NSString stringWithFormat:@"json: @%", json]); 

Solution

  • that is using the key-value coding from the (NSObject) category,

    to use the dictionary interface: import JSON.h then:

        NSMutableDictionary * dict = [NSMutableDictionary new];
        [dict setValue:@"val" forKey:@"key"];
    
        NSLog(@"json: %@", [dict JSONRepresentation]);
    

    p.s. NSLog accepts a format, so you don't need to make a string from a format to pass to it.