How to serialize the following class in objective-c so that it can be used with SBJson?
I get \"JSON serialisation not supported for Animal\" error when I use this c
To actually answer your question on how to do it using SBJson: Implement the proxyForJson
method. Unless you are serializing an NSArray
or NSDictionary
you must override this method for serialization to work.
You can see that this is the case by looking at the SBJson source code (in SBJsonWriter.m):
- (NSData*)dataWithObject:(id)object {
...
if ([object isKindOfClass:[NSDictionary class]])
ok = [streamWriter writeObject:object];
else if ([object isKindOfClass:[NSArray class]])
ok = [streamWriter writeArray:object];
else if ([object respondsToSelector:@selector(proxyForJson)])
return [self dataWithObject:[object proxyForJson]];
else {
self.error = @"Not valid type for JSON";
return nil;
}
...
}
}
Implement proxyForJson
in Animal.m
like this (not tested):
- (NSDictionary*) proxyForJson
{
return [NSDictionary dictionaryWithObjectsAndKeys:self.name, @"name",
self.description, @"description",
self.imageURL, @"imageURL",
nil];
}