logo头像
Snippet 博客主题

JsonModel的使用

基本使用

initWithDictionary使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@interface Person : JSONModel

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, assign) NSInteger age;

@end

NSDictionary *dict = @{
@"name":@"Jack",
@"age":@23,
@"gender":@"male",
};
NSError *error;
Person *person = [[Person alloc] initWithDictionary:dict error:&error];


key值转换

原来字典里的gender这个key变成了sex,这就需要我们定义一个转换的mapper(JSONKeyMapper):

1
2
3
4
5
6
7
8
9
10
11
12


@implementation Person

+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
@"gender": @"sex",
}];
}


自定义错误

比如,当age对应的数值小于25的时候,打印出Too young!,并阻止模型的转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

- (BOOL)validate:(NSError **)error
{
if (![super validate:error])
return NO;

if (self.age < 25)
{
*error = [NSError errorWithDomain:@"Too young!" code:10 userInfo:nil];
NSError *errorLog = *error;
NSLog(@"%@",errorLog.domain);
return NO;
}

return YES;
}


类型自动匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

{ "id": "10", "country": "Germany", "dialCode": 49, "isInEurope": true }



#import "JSONModel.h"

@interface CountryModel : JSONModel

@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* country;
@property (strong, nonatomic) NSString* dialCode;
@property (assign, nonatomic) BOOL isInEurope;

@end


如果传过来的JSON合法,你所定义的所有的属性都会与该JSON的值想对应,甚至JSONModel会尝试去转换数据为你期望的类型,如上所示:

- 转换id,从字符串转换为int
- 只需要拷贝一下country的值
- 转换diaCode,从number转换为字符串
- 最后一个是将isInEurope转换为BOOL属性
`所以,你所需要做的就是将你的属性定义为期望的类型.`

模型嵌套、模型集合

举个例子,我们让上面的Person对象含有一个数组Friends,它里面的元素是对象Friend,也就是好友信息。若要实现模型的嵌套,我们只需在原来的模型类里增加一个协议Friend:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#import "JSONModel.h"
@protocol Friend;

@interface Friend : JSONModel

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;

@end


@interface Person : JSONModel

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, strong) NSArray<Friend> *friends;//数组,嵌套模型

@end

key映射

服务器返回数据

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

{
"order_id": 104,
"order_details" : [
{
"name": "Product#1",
"price": {
"usd": 12.95
}
}
]
}

可以随意改对应的字段,可以随意取对应的数据,很强大

@interface OrderModel : JSONModel
@property (assign, nonatomic) int id;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSString* productName;
@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{
@"order_id": @"id",
@"order_details.name": @"productName",
@"order_details.price.usd": @"price"
}];
}


设置全局键映射(应用于所有model)

1
2
3
4
5
6
7
8

[JSONModel setGlobalKeyMapper:[
[JSONKeyMapper alloc] initWithDictionary:@{
@"item_id":@"ID",
@"item.name": @"itemName"
}]
];

设置下划线自动转驼峰

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

{
"order_id": 104,
"order_product" : @"Product#1",
"order_price" : 12.95
}

@interface OrderModel : JSONModel

@property (assign, nonatomic) int orderId;
@property (assign, nonatomic) float orderPrice;
@property (strong, nonatomic) NSString* orderProduct;

@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
}

@end


可选属性 (就是说这个属性可以为null或者为空)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

{
"id": "123",
"name": null,
"price": 12.95
}


@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Optional>* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSNumber<Optional>* uuid;
@end

@implementation ProductModel
@end

忽略属性 (就是完全忽略这个属性)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

{
"id": "123",
"name": null
}



@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Ignore>* customProperty;
@end

@implementation ProductModel
@end


设置所有的属性为可选(所有属性值可以为空)

1
2
3
4
5
6
7
8

@implementation ProductModel
+(BOOL)propertyIsOptional:(NSString*)propertyName
{
return YES;
}
@end

使用JSONModel自带的 HTTP 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14

//add extra headers
[[JSONHTTPClient requestHeaders] setValue:@"MySecret" forKey:@"AuthorizationToken"];

//make post, get requests
[JSONHTTPClient postJSONFromURLWithString:@"http://mydomain.com/api"
params:@{@"postParam1":@"value1"}
completion:^(id json, JSONModelError *err) {

//check err, process json ...

}];


将model转化为字典或者json格式的字符串

1
2
3
4
5
6
7
8
9
ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil];
pm.name = @"Changed Name";

//convert to dictionary
NSDictionary* dict = [pm toDictionary];

//convert to text
NSString* string = [pm toJSONString];

自定义数据的转换

自定义处理指定的属性

自定义JSON校验

源码解析

JSONModel源码解析

参照博客

iOS中JSONModel的使用

微信打赏

赞赏是不耍流氓的鼓励