『IOS』JSONModel解析Dictionary To Model ,JSON到Model

来源:互联网 发布:java排序库函数 编辑:程序博客网 时间:2024/06/04 01:32

插曲:IOS学习笔记38——NSJSONSerialization使用

如何解析JSON格式的数据,JSON数据结构以其轻量化的结构体和良好的可读性被越来越广泛的运用,特别在移动开发上,手机的流量是宝贵资源,更要求使用轻量级的数据格式进行数据传输。关于在iOS平台上进行JSON解析,已经有很多第三方的开源项目,比如SBJson、JSONFramwork等,用的也非常广泛,自从iOS5.0以后,苹果推出了SDK自带的JSON解决方案NSJSONSerialization,这是一个非常好用的JSON生成和解析工具,效率也是比其他第三方开源项目的高很多,详情可查看Developer Guider。当然还有下文的jsonmodel


查看原文:http://www.heyuan110.com/?p=1155

你在把字典转成object的时候还在按下面这样:

self.id = [jsonDict objectForKey:@"id"]; self.name = [jsonDict objectForKey:@"name"]; self.profileImageBig = [jsonDict objectForKey:@"profile_image_big"]; self.profileImageSmall = [jsonDict objectForKey:@"profile_image_small"]; self.profileImageSquare = [jsonDict objectForKey:@"profile_image_square"]; self.firstName = [jsonDict objectForKey:@"firstName"]; self.familyName = [jsonDict objectForKey:@"familyName"]; self.age = [jsonDict objectForKey:@"age"];

这样做你就out了,繁琐而且麻烦,得判断值的nil,null,类型等。使用JSONModel这样即可搞定

@interface MyModel: JSONModel @property (strong, nonatomic) NSString* id; @property (strong, nonatomic) NSString* name; (etc...) @end

添加JSONModel的方式

pod管理的直接 pod 'JSONModel'

其它的直接去下载包:https://github.com/icanzilb/JSONModel

教程参考:

http://www.touch-code-magazine.com/JSONModel/

http://www.raywenderlich.com/12139/introduction-to-cocoapods

简单介绍一下几个方面

  1. 例如 @property (strong, nonatomic) NSString<index>* name;你看到有一个Index,这个表示指定一个索引,作用就是可以直接在数组中查找符合条件的对象,例如查找数组中object的name是sharofat的对象可以像下面这样写:

    //查找index为sharofat的 NSArray *loans = feed.loans; NSLog(@"modelWithIndexValue --->%@",[loans modelWithIndexValue:@"Sharofat"]);
  2. object的数组和dict的数组相互转换,objce转json,dict

    //将model的array转成dict的array NSMutableArray *dictArray = [LoanModel arrayOfDictionariesFromModels:feed.loans]; NSLog(@"arrayOfDictionariesFromModels===>%@",dictArray); //将dict的array转成model的array NSMutableArray *modelArray = [LoanModel arrayOfModelsFromDictionaries:dictArray]; NSLog(@"arrayOfModelsFromDictionaries===>%@",modelArray); LoanModel* loan = feed.loans[indexPath.row]; NSLog(@"loan.toDictionary--->%@",loan.toDictionary); NSLog(@"loan.toJSONString--->%@",loan.toJSONString);
  3. json,dict转object时判断value

    -(BOOL)validate:(NSError**)err { if ([self.name isEqual:@"Winfred"]) { self.name = @"Winfred rewrite name"; // return NO; } NSLog(@"Loan of %@", self.name); NSLog(@"sector of %@", self.modelSector); NSLog(@"plandate of %@", self.plandate); return YES; }
  4. 很重要的keyMapper,指定映射值,如果不指定就是默认的

    • 转换带下划线的,例如:user_name 转换对应的key就是userName

      +(JSONKeyMapper*)keyMapper { return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase]; }
    • 自定义key,例如: planned_expiration_date转换想对应plandate

      +(JSONKeyMapper*)keyMapper { return [[JSONKeyMapper alloc] initWithJSONToModelBlock:^NSString *(NSString *keyName) { if ([keyName isEqual:@"planned_expiration_date"]) { return @"plandate"; }else if ([keyName isEqual:@"sector"]) { return @"modelSector"; } else { return keyName; } } modelToJSONBlock:^NSString *(NSString *keyName) { if ([keyName isEqual:@"plandate"]) { return @"planned_expiration_date"; }else if ([keyName isEqual:@"modelSector"]) { return @"sector"; }else { return keyName; } }]; }

      也可以像下面这样写:

      +(JSONKeyMapper*)keyMapper { return [[JSONKeyMapper alloc]initWithDictionary:@{@"sector":@"modelSector"}]; }
  5. 指定定义的key的类型

    • <optional>表示字段可选,例如

      //链接字段是可选的,转换的时候允许link未空 @property (nonatomic,strong) NSString</optional><optional> *link;
    • <index>表示索引,参照1

    • <convertondemand>转换对象数组,例如:

      //表示数组是LoanModel对象 @property (strong, nonatomic) NSArray<loanmodel , ConvertOnDemand>* loans;

apple funcdation中的NSJSONSerialization
//AppDelegate.m...Message* message1 = [[Message alloc] init];Message* message2 = [[Message alloc] init];message1.from = @"a";message1.date = @"b";message1.msg = @"c";message2.from = @"d";message2.date = @"e";message2.msg = @"f";NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil];[message1 release];[message2 release];NSError *writeError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"JSON Output: %@", jsonString);@end

The output when I run the application is thus:

2012-05-11 11:58:36.018 stack[3146:f803] JSON Output: [ { "msg" : "c", "from" : "a", "date" : "b" }, { "msg" : "f", "from" : "d", "date" : "e" } ]



0 0
原创粉丝点击