您可以为您的自定义模型类(例如,CountryModel
)定义一个实现类工厂方法的类别。一个人为的例子:
@interface CountryModel (JSONExtension)
+ (CountryModel*) jsonExtension_modelWithJSONObject:(NSDictionary*)jsonObject error:(NSError**)error;
@end
@implementation CountryModel (JSONExtension)
+ (CountryModel*) jsonExtension_modelWithJSONObject:(NSDictionary*)jsonObject error:(NSError**)error {
// Create an object of type Foo with the given NSDictionary object
CountryModel* result = [[CountryModel alloc] initWithName:jsonObject[@"name"]];
if (result == nil) {
if (error) {
*error = [NSError errorWithDomain:@"CountryModel"
code:-100
userInfo:@{NSLocalizedDescriptionKey: @"Could not initialize CountryModel with JSON Object"}];
}
return nil;
}
// "recursively" use jsonExtension_modelWithJSONObject:error: in order to initialize internal objects:
BarModel* bar = [BarModel jsonExtension_modelWithJSONObject:jsonObject[@"bar"] error:error];
if (bar == nil) // bar is required
{
result = nil;
return nil;
}
result.bar = bar;
return result;
}
@end
的JSONObject是JSON对象作为NSDictionary
对象的表示。您需要先通过类工厂方法创建此表示形式,例如:
NSError* error;
NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
assert([jsonObject isKindOfClass[NSDictionary class]]);
CountryModel* model = [CountryModel jsonExtension_modelWithJSONObject:jsonObject error:&error];