0%

BaseDataModel示例(1)-创建一个基于BaseDataModel的模型

创建一个基于 BaseDataModel的模型 Model based on BaseDataModel

1. 基本模型 Normal model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@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));
}

相关

更新内容

相关链接调整。