平时做开发经常用到json数据,这时候往往需要把json转换成程序内部的model方便做进一步的处理。推荐一款第三方工具Mantle。
基本实现步骤
1
2
3
4
5
6
7
| 1.下载 https://github.com/Mantle/Mantle
2. 创建一个Model 类 ,继承自MTLModel
3. 实现映射协议 MTLJSONSerializing。协议里有一个require方法 JSONKeyPathsByPropertyKey
4. 对于一些需要特殊处理的需要实现自适应的属性转换方法,该方法对于命名有一定要求,属性命+JSONTransformer
|
举例
json原型如下
1
2
3
4
| dic {
id = 10;
name = xiangrikui;
}
|
model.h
1
2
3
4
5
6
7
| #import "MTLModel.h"
#import <Mantle/MTLJSONAdapter.h>
@interface Picture : MTLModel<MTLJSONSerializing>
@property (nonatomic,copy) NSString *id;
@property (nonatomic,copy) NSString *picName;
@end
|
.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #import "Picture.h"
#import <Mantle/MTLValueTransformer.h>
@implementation Picture
+ (NSDictionary *)JSONKeyPathsByPropertyKey{
return @{
@"id":@"id",
@"picName":@"name"
};
}
+ (NSValueTransformer *)picNameJSONTransformer {
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSString *name) {
return [name stringByAppendingString:@"_xx"];
} reverseBlock:^id(NSString *name) {
return [name substringToIndex:name.length-4];
}];
}
@end
|
vc里的调用方式
1
| Picture *picture = [MTLJSONAdapter modelOfClass:[Picture class] fromJSONDictionary:dic error:nil];
|
原创作品,转载请注明出处,谢谢。