1. //
  2. // HYBJSONModel.h
  3. // Json2ModelDemo
  4. //
  5. // Created by huangyibiao on 14-9-15.
  6. // Copyright (c) 2014年 Home. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10.  
  11. /*!
  12. * @brief JSON转换成Model,或者把Model转换成JSON
  13. * @author huangyibiao
  14. */
  15. @interface HYBJSONModel : NSObject
  16.  
  17. /*!
  18. * @brief 把对象(Model)转换成字典
  19. * @param model 模型对象
  20. * @return 返回字典
  21. */
  22. + (NSDictionary *)dictionaryWithModel:(id)model;
  23.  
  24. /*!
  25. * @brief 获取Model的所有属性名称
  26. * @param model 模型对象
  27. * @return 返回模型中的所有属性值
  28. */
  29. + (NSArray *)propertiesInModel:(id)model;
  30.  
  31. /*!
  32. * @brief 把字典转换成模型,模型类名为className
  33. * @param dict 字典对象
  34. * @param className 类名
  35. * @return 返回数据模型对象
  36. */
  37. + (id)modelWithDict:(NSDictionary *)dict className:(NSString *)className;
  38.  
  39. @end
  1. //
  2. // HYBJSONModel.m
  3. // Json2ModelDemo
  4. //
  5. // Created by huangyibiao on 14-9-15.
  6. // Copyright (c) 2014年 Home. All rights reserved.
  7. //
  8.  
  9. #import "HYBJSONModel.h"
  10. #import <objc/runtime.h>
  11.  
  12. typedef NS_ENUM(NSInteger, HYBJSONModelDataType) {
  13. kHYBJSONModelDataTypeObject = ,
  14. kHYBJSONModelDataTypeBOOL = ,
  15. kHYBJSONModelDataTypeInteger = ,
  16. kHYBJSONModelDataTypeFloat = ,
  17. kHYBJSONModelDataTypeDouble = ,
  18. kHYBJSONModelDataTypeLong = ,
  19. };
  20.  
  21. @implementation HYBJSONModel
  22.  
  23. /*!
  24. * @brief 把对象(Model)转换成字典
  25. * @param model 模型对象
  26. * @return 返回字典
  27. */
  28. + (NSDictionary *)dictionaryWithModel:(id)model {
  29. if (model == nil) {
  30. return nil;
  31. }
  32.  
  33. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  34.  
  35. // 获取类名/根据类名获取类对象
  36. NSString *className = NSStringFromClass([model class]);
  37. id classObject = objc_getClass([className UTF8String]);
  38.  
  39. // 获取所有属性
  40. unsigned int count = ;
  41. objc_property_t *properties = class_copyPropertyList(classObject, &count);
  42.  
  43. // 遍历所有属性
  44. for (int i = ; i < count; i++) {
  45. // 取得属性
  46. objc_property_t property = properties[i];
  47. // 取得属性名
  48. NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
  49. encoding:NSUTF8StringEncoding];
  50. // 取得属性值
  51. id propertyValue = nil;
  52. id valueObject = [model valueForKey:propertyName];
  53.  
  54. if ([valueObject isKindOfClass:[NSDictionary class]]) {
  55. propertyValue = [NSDictionary dictionaryWithDictionary:valueObject];
  56. } else if ([valueObject isKindOfClass:[NSArray class]]) {
  57. propertyValue = [NSArray arrayWithArray:valueObject];
  58. } else {
  59. propertyValue = [NSString stringWithFormat:@"%@", [model valueForKey:propertyName]];
  60. }
  61.  
  62. [dict setObject:propertyValue forKey:propertyName];
  63. }
  64. return [dict copy];
  65. }
  66.  
  67. /*!
  68. * @brief 获取Model的所有属性名称
  69. * @param model 模型对象
  70. * @return 返回模型中的所有属性值
  71. */
  72. + (NSArray *)propertiesInModel:(id)model {
  73. if (model == nil) {
  74. return nil;
  75. }
  76.  
  77. NSMutableArray *propertiesArray = [[NSMutableArray alloc] init];
  78.  
  79. NSString *className = NSStringFromClass([model class]);
  80. id classObject = objc_getClass([className UTF8String]);
  81. unsigned int count = ;
  82. objc_property_t *properties = class_copyPropertyList(classObject, &count);
  83.  
  84. for (int i = ; i < count; i++) {
  85. // 取得属性名
  86. objc_property_t property = properties[i];
  87. NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
  88. encoding:NSUTF8StringEncoding];
  89. [propertiesArray addObject:propertyName];
  90. }
  91.  
  92. return [propertiesArray copy];
  93. }
  94.  
  95. /*!
  96. * @brief 把字典转换成模型,模型类名为className
  97. * @param dict 字典对象
  98. * @param className 类名
  99. * @return 返回数据模型对象
  100. */
  101. + (id)modelWithDict:(NSDictionary *)dict className:(NSString *)className {
  102. if (dict == nil || className == nil || className.length == ) {
  103. return nil;
  104. }
  105.  
  106. id model = [[NSClassFromString(className) alloc]init];
  107.  
  108. // 取得类对象
  109. id classObject = objc_getClass([className UTF8String]);
  110.  
  111. unsigned int count = ;
  112. objc_property_t *properties = class_copyPropertyList(classObject, &count);
  113. Ivar *ivars = class_copyIvarList(classObject, nil);
  114.  
  115. for (int i = ; i < count; i ++) {
  116. // 取得成员名
  117. NSString *memberName = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
  118. const char *type = ivar_getTypeEncoding(ivars[i]);
  119. NSString *dataType = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
  120.  
  121. NSLog(@"Data %@ type: %@",memberName,dataType);
  122.  
  123. HYBJSONModelDataType rtype = kHYBJSONModelDataTypeObject;
  124. if ([dataType hasPrefix:@"c"]) {
  125. rtype = kHYBJSONModelDataTypeBOOL;// BOOL
  126. } else if ([dataType hasPrefix:@"i"]) {
  127. rtype = kHYBJSONModelDataTypeInteger;// int
  128. } else if ([dataType hasPrefix:@"f"]) {
  129. rtype = kHYBJSONModelDataTypeFloat;// float
  130. } else if ([dataType hasPrefix:@"d"]) {
  131. rtype = kHYBJSONModelDataTypeDouble; // double
  132. } else if ([dataType hasPrefix:@"l"]) {
  133. rtype = kHYBJSONModelDataTypeLong;// long
  134. }
  135.  
  136. for (int j = ; j < count; j++) {
  137. objc_property_t property = properties[j];
  138. NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
  139. encoding:NSUTF8StringEncoding];
  140. NSRange range = [memberName rangeOfString:propertyName];
  141.  
  142. if (range.location == NSNotFound) {
  143. continue;
  144. } else {
  145. id propertyValue = [dict objectForKey:propertyName];
  146.  
  147. switch (rtype) {
  148. case kHYBJSONModelDataTypeBOOL: {
  149. BOOL temp = [[NSString stringWithFormat:@"%@", propertyValue] boolValue];
  150. propertyValue = [NSNumber numberWithBool:temp];
  151. }
  152. break;
  153. case kHYBJSONModelDataTypeInteger: {
  154. int temp = [[NSString stringWithFormat:@"%@", propertyValue] intValue];
  155. propertyValue = [NSNumber numberWithInt:temp];
  156. }
  157. break;
  158. case kHYBJSONModelDataTypeFloat: {
  159. float temp = [[NSString stringWithFormat:@"%@", propertyValue] floatValue];
  160. propertyValue = [NSNumber numberWithFloat:temp];
  161. }
  162. break;
  163. case kHYBJSONModelDataTypeDouble: {
  164. double temp = [[NSString stringWithFormat:@"%@", propertyValue] doubleValue];
  165. propertyValue = [NSNumber numberWithDouble:temp];
  166. }
  167. break;
  168. case kHYBJSONModelDataTypeLong: {
  169. long long temp = [[NSString stringWithFormat:@"%@",propertyValue] longLongValue];
  170. propertyValue = [NSNumber numberWithLongLong:temp];
  171. }
  172. break;
  173.  
  174. default:
  175. break;
  176. }
  177.  
  178. [model setValue:propertyValue forKey:memberName];
  179. break;
  180. }
  181. }
  182. }
  183. return model;
  184. }
  185.  
  186. @end

IOS Dictionary和Model相互转换的更多相关文章

  1. 【AutoMapper官方文档】DTO与Domin Model相互转换(下)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  2. ios中常用数据类型相互转换

    ios中常用数据类型相互转换 //1. NSMutableArray和NSArray互转 // NSArray转为NSMutableArray NSMutableArray *arrM = [arr ...

  3. 【AutoMapper官方文档】DTO与Domin Model相互转换(上)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  4. 【AutoMapper官方文档】DTO与Domin Model相互转换(中)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  5. iOS 字典与JSON相互转换

    iOS 字典与JSON相互转换 首先简单说一下为什么会写这种幼稚的文章. 现在的网络请求几乎都是AFN完成的,AFN也为我们写了了JSON转换字典的方法,但是不要忘记后台是一个很爱用JSON的人群,H ...

  6. iOS标准时间与时间戳相互转换

    iOS标准时间与时间戳相互转换 (2012-07-18 17:03:34) 转载▼ 标签: ios 时间戳 标准时间 格式 设置 转化 杂谈 分类: iPhone开发 设置时间显示格式:     NS ...

  7. 判断iOS系统的Model

    获取iOS系统的Model   (参考网址:https://www.theiphonewiki.com/wiki/Models) + (NSString *)getModel{ struct utsn ...

  8. C# 类型转换 Dictionary转Model类

    /// <summary> /// 把Model转换为DataRow /// </summary> /// <typeparam name="T"&g ...

  9. Dictionary转为Model实例

    Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add(); dic.Add(&q ...

随机推荐

  1. 用VS2005写一个 C 的类库和用 C#来调用的示例

    一.用VS2005写一个 C 的类库的步骤: (1).建立一个空的Visual C++项目 (2).这时候在项目中可以看见 三个空目录 选中 "源文件" 目录,然后点鼠标右键,在弹 ...

  2. aix7安装was7、打补丁、更改访问端口、手动启动was、配置was7、部署项目

    1:准备工作  首先了解下我们下面即将用到的aix命令,以及安装包.补丁安装工具.补丁 was7的安装包以及补丁工具都是压缩包形式并且以.tar.gz结尾的 安装包在800MB左右,通常为****_w ...

  3. js获取屏幕(设备)宽高

    平常获取设备的宽高无非就那几 <script language="javascript"> var h = ""; h += " 网页可见 ...

  4. AspNet WebApi : MessageHandler(消息处理器 )

    1. Http Message Handler WebApi中的MessageHandler类似MVC中的filter,可用于请求/响应到达真正目标前对请求或者响应进行修改,比如:用户身份验证,请求头 ...

  5. 那些年被我坑过的Python——不得不知(第二章)

    问题一: Python3.5.X中的数据类型有哪些? 答:包括整型.布尔型.字符串型.浮点型.复数.列表.字典.集合.元组. 细化来说: 1.整型包括短整型和长整型,不过我们不必过度操心细节,因为短整 ...

  6. Vim C/C++的一键编译

    开始用Vim差不多有两个月的时间, 一开始用Makefile 编译一整个项目无压力, 但是当写到单个文件的时候, 编译就比较麻烦了, 每次都得 :w :!gcc -o 1.exe 1.c :!1 非常 ...

  7. 转载:.NET Web开发技术简单整理

    在最初学习一些编程语言.一些编程技术的时候,做的更多的是如何使用该技术,如何更好的使用该技术解决问题,而没有去关注它的相关性.关注它的理论支持,这种学习技术的方式是短平快.其实工作中有时候也是这样,公 ...

  8. ECMAScript 6 模块简介

    任何平台的其中一个重要特性,除了需要支持代码库外就是模块.直到现在,Javascript还不支持原生的模块化.结果是,各种解决方案都将模块添加到类库中,比如CommonJS modules(部分由no ...

  9. BZOJ 1501 智慧珠游戏

    Description Input 文件中包含初始的盘件描述,一共有10行,第i行有i个字符.如果第i行的第j个字符是字母”A”至”L”中的一个,则表示第i行第j列的格子上已经放了零件,零件的编号为对 ...

  10. [BZOJ 1055] [HAOI2008] 玩具取名 【记忆化搜索】

    题目链接:BZOJ - 1055 题目分析 这种类似区间 DP 的记忆化搜索都是很相近的,比如字符串压缩和字符串扩展都差不多. 都是将现在 Solve 的区间分成子区间,再求解子区间. 这道题 Sol ...