Search code examples
ios5nsdictionarynsjsonserializationcustom-object

How to serialize a custom object in NSDictionary using JSON?


I have the following code:

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"one", @"oneKey", 
@"two", @"twoKey", customObject, @"customObjectKey", nil];
if([NSJSONSerialization isValidJSONObject:dict])
{
    NSLog(@"Went through.");
}

It'll go through if the objects were NSString's, but once I added the customObject into the dictionary, it's no longer valid. How can I fix that? Any help is much appreciated. Thanks in advance!


Solution

  • You would require to use NSCoding protocol to serialize a custom object.

    Implement the NSCoding protocol in .h file and implement the following methods in .m file of your custom class.

    - (id)initWithCoder:(NSCoder *)aDecoder
    {
       if(self = [super init]) // this needs to be [super initWithCoder:aDecoder] if the superclass implements NSCoding
       {
          aString = [[aDecoder decodeObjectForKey:@"aStringkey"] retain];
          anotherString = [[aDecoder decodeObjectForKey:@"anotherStringkey"] retain];
       }
       return self;
    }
    

    and

    - (void)encodeWithCoder:(NSCoder *)encoder
    {
       // add [super encodeWithCoder:encoder] if the superclass implements NSCoding
       [encoder encodeObject:aString forKey:@"aStringkey"];
       [encoder encodeObject:anotherString forKey:@"anotherStringkey"];
    }