How to serialize a class in IOS sdk (Objective-c)?

前端 未结 7 1588
既然无缘
既然无缘 2021-01-03 01:21

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

7条回答
  •  伪装坚强ぢ
    2021-01-03 01:50

    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];
    }
    

提交回复
热议问题