在代码中:
+ (NSString *)JSONString;
(+
加号)表示一个类方法。您很可能需要一个实例方法,如下所示:
- (NSString *)JSONString;
关于如何实现序列化的方法:这是相当“旁白”。你所问的范围很广,你给出的细节很少。这实际上取决于您的需求范围以及您想要投入多少时间/精力,但要权衡一下意见:
一个类别对NSObject
我来说似乎有点过于宽泛。我认为它不太可能产生比看起来更合乎逻辑的选择协议更好的结果。
坦率地说,我希望NSJSONSerialization
声明一个用于序列化我们自己的自定义模型对象的协议,类似于NSCoding
,但他们没有。这仍然是我将对象编码为JSON
. 协议可能看起来像这样:
NSString * const MySerializationClassKey = @"MySerializationClassKey";
@protocol MySerializationProtocol <NSObject>
@required
-(NSDictionary *)dictionarySerialization;
-(id)initFromDictionarySerialization:(NSDictionary *)dictionary;
@end
然后您的自定义模型对象可以像这样序列化和反序列化:(过于简单化)
@interface MyModel() <MySerializationProtocol>
@property (strong) NSString *name;
@end
@implementation MyModel
NSString * const MyModelNameKey = @"MyModelNameKey";
@synthesize name = _name;
-(NSDictionary *)dictionarySerialization{
// encode object as dictionary
return @{MySerializationClassKey: NSStringFromClass(self.class), MyModelNameKey: _name.copy};
}
-(id)initFromDictionarySerialization:(NSDictionary *)dictionary{
if ((self = [super init])){
_name = [dictionary objectForKey:MyModelNameKey];
}
return self;
}
@end
现在假设,为了不将完整的序列化库输入到答案中,您只拥有NSArray
这些模型对象的平面。您可以创建一个NSJSONSerialization
与这些方法配合使用的类。为了使每次通话更轻松,如下所示:
@interface MySerializer : NSObject
@end
@implementation MySerializer
+(NSData *)jsonDataFromObject:(NSMutableArray *)array{
for (NSUInteger index = 0; index < array.count; index++) {
NSObject *object = [array objectAtIndex:index];
if ([object conformsToProtocol:@protocol(MySerializationProtocol)]){
NSDictionary *dictRep = [(id<MySerializationProtocol>)object dictionarySerialization];
[array replaceObjectAtIndex:index withObject:dictRep];
}
}
return [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
}
+(NSMutableArray *)objectFromJSONData:(NSData *)data{
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSUInteger index = 0; index < array.count; index++) {
NSObject *object = [array objectAtIndex:index];
if ([object isKindOfClass:[NSDictionary class]]){
NSDictionary *dict = (NSDictionary *)object;
NSString *className = [dict objectForKey:MySerializationClassKey];
if (className.length > 0) {
NSObject *deserialized = [[NSClassFromString(className) alloc] initFromDictionarySerialization:dict];
if (deserialized) [array replaceObjectAtIndex:index withObject:deserialized];
}
}
}
return array;
}
@end
现在显然要从这样的代码中获得任何里程,您必须递归遍历可能的数组和字典。但这是我的首选路线。