JSONModel使用「数据转模型」
一、准备JSONModel_下载
配合ESJsonFormat插件效果更佳!
二、基本使用
{ "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
初始化你的 model,如下所示: #import "CountryModel.h" ... NSString* json = (fetch here JSON from Internet) ... NSError* err = nil; CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];
所以,你需要做的就是定义出你期望的属性就行了。 三、例子
1.命名自动匹配
2.Model关联(model含有其他model)
3.Model集合(model含有其他model的集合)
NSArry后的就<>中包含一个协议,这并不是Objective-C的新语法,他们不会冲突,使用JSONModel必须实现这个协议!
4.键映射
5.设置全局键映射(应用于所有model)
6.设置下划线自动转驼峰
7.可选属性(属性值可以为空或null)
8.忽略属性(属性值可以完全忽略)
9.设置所有属性可选(所有属性值可以为空)
10.使用内置的HTTP链接//添加额外的头 [[JSONHTTPClient requestHeaders] setValue:@"MySecret" forKey:@"AuthorizationToken"]; //设置GET,POST请求 [JSONHTTPClient postJSONFromURLWithString:@"http://mydomain.com/api" params:@{@"postParam1":@"value1"} completion:^(id json,JSONModelError *err) { //检查错误,处理JSON }]; 11.将Model导出字典或JOSN字符串
ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil]; pm.name = @"Changed Name"; //以字典形式导出 NSDictionary* dict = [pm toDictionary]; //以字符串形式导出 NSString* string = [pm toJSONString]; 12.自定义数据处理
@implementation JSONValueTransformer (CustomTransformer) //时间戳转NSDate - (NSDate *)NSDateFromNSString:(NSString*)string { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:APIDateFormat]; return [formatter dateFromString:string]; } //NSDate转时间戳 - (NSString *)JSONObjectFromNSDate:(NSDate *)date { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:APIDateFormat]; return [formatter stringFromDate:date]; } @end 13.自定义处理特殊属性@interface ProductModel : JSONModel @property (assign,nonatomic) NSString* name; @property (assign,nonatomic) float price; @property (strong,nonatomic) NSLocale *locale; @end @implementation ProductModel //处理本地化标识后给locale赋值 - (void)setLocaleWithNSString:(NSString*)string { self.locale = [NSLocale localeWithLocaleIdentifier:string]; } - (NSString *)JSONObjectForLocale { return self.locale.localeIdentifier; } @end 14.自定义JSON验证@interface ProductModel : JSONModel @property (assign,nonatomic) NSLocale *locale; @property (strong,nonatomic) NSNumber <Ignore> *minNameLength; @end @implementation ProductModel - (BOOL)validate:(NSError *__autoreleasing *)error { BOOL valid = [super validate:error]; if (self.name.length < self.minNameLength.integerValue) { *error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil]; valid = NO; } return valid; } @end
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |