直奔主题:在ios平台作通用的json数据解析,直接将json格式字符串转化成 对应的Object类(好比:jsonUser 转 User对象)。html
思路: 1. 获取服务器端的json数据,而后解析成NSDictionary对象(咱们通常是使用第三方的json解析工具JSONKit,SBJson等)。ios
2. 使用第三方工具Jastor将NSDictionary 转成 响应Object对象。git
ok,如今跟你们列出关键代码:github
1.首先我使用的JSONkit将json字符串解析为NSDictionary对象(参考:http://blog.csdn.net/ck89757/article/details/7842846 )json
//objectFromJSONData直接使用data转字典 NSData *data = [@"{\"name\":\"hanqing\",\"age\":\"23\"}" dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *result = [data objectFromJSONData];//JSONKit中的解析函数 objectFromJSONData
2.建立Object对象,使用Jastor 将NSDictionary 转成 Product对象 (Jastor下载和用法参考https://github.com/elado/jastor,在该地址下载下Jastor包后,直接将Jastor文件夹拉到ios项目中,只有4个文件Jastor.h、Jastor.m、JastorRuntimeHelper.h、JastorRuntimeHelper.m) 服务器
// Product.h @interface Product : Jastor//必定要继承Jastor类 @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSNumber *amount; @end // Product.m @implementation Product @synthesize name, amount; @end // 关键代码 Product *product = [[Product alloc] initWithDictionary:result];//Jastor中的转化函数
3.如何将 NSObject 转成 JSON 其中,咱们采用了一个折中的方式,将NSOBject转换成 字典,而后采用 JSONkit 转换成 JSON函数
- (NSString *)convertFromObject{ NSMutableDictionary *returnDic = [[NSMutableDictionaryalloc] init]; NSArray *array =[JastorRuntimeHelperpropertyNames:[selfclass]];//获取全部的属性名称 for (NSString *key in array) { [returnDic setValue:[selfvalueForKey:key] forKey:key];//从类里面取值而后赋给每一个值,取得字典 } NSString returnString = [returnDic JSONString];//齐刷刷的变成JSON吧 return returnString ; }
转载标明出处:http://write.blog.csdn.net/postedit/7927744工具