创建一个基于 BaseDataModel的模型 model based on BaseDataModel
1. 基本模型 normal model
@interface User : BaseDataModel
@property (copy, nonatomic, nullable) NSString<Optional> *nick;
@property (strong, nonatomic, nullable) NSNumber<Optional> *age;
@end
@implementation User
+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
@"dataID": @"ID", // dataID用作ID
@"dataName": @"name" // dataName用作name
}];
}
@end
// Test
NSDictionary *dictionary = @{@"ID": @59,
@"name": [NSNull null],
@"nick": @"Tony",
@"age": [NSNull null],
@"offline": @true};
NSError *error;
User *model = [[User alloc] initWithDictionary:dictionary error:&error];
if (model) {
LOG_FORMAT(@"%@", STRING_FORMAT(@"model: %@", model));
}
2. 含嵌套模型 with embed model based on BaseDataModel
@interface ContactInfoModel : BaseDataModel
@property (copy, nonatomic, nullable) NSString<Optional> *address;
@property (copy, nonatomic, nullable) NSString<Optional> *mobilephone;
@property (copy, nonatomic, nullable) NSString<Optional> *email;
@end
@protocol ContactInfoModel <NSObject>
@end
@interface User : BaseDataModel
@property (copy, nonatomic, nullable) NSString<Optional> *nick;
@property (strong, nonatomic, nullable) NSNumber<Optional> *age;
@property (strong, nonatomic, nullable) ContactInfoModel<Optional> *contactInfo;
@end
@implementation ContactInfoModel
@end
@implementation User
+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
@"dataID": @"ID", // dataID用作ID
@"dataName": @"name" // dataName用作name
}];
}
@end
//Test
NSDictionary *dictionary = @{@"ID": @59,
@"name": [NSNull null],
@"nick": @"Tony",
@"age": [NSNull null],
@"contactInfo": @{@"address": [NSNull null],
@"mobilephone": @"136xxxxxxxx",
@"email": [NSNull null]},
@"offline": @true};
NSError *error;
User *model = [[User alloc] initWithDictionary:dictionary error:&error];
if (model) {
LOG_FORMAT(@"%@", STRING_FORMAT(@"model: %@", model));
}
相关
- 详见极致框架官网<extreme.framework/BaseDataModel.h>的介绍。通过极致框架官网顶部的搜索功能搜索 BaseDataModel。
许可
- 本文采用 BY-NC-SA 许可协议。即:署名——转载请注明出处;非商业使用;相同方式传播——再分发的文章许可与原文相同。
网友评论