IOS Dictionary和Model相互转换
//
// HYBJSONModel.h
// Json2ModelDemo
//
// Created by huangyibiao on 14-9-15.
// Copyright (c) 2014年 Home. All rights reserved.
// #import <Foundation/Foundation.h> /*!
* @brief JSON转换成Model,或者把Model转换成JSON
* @author huangyibiao
*/
@interface HYBJSONModel : NSObject /*!
* @brief 把对象(Model)转换成字典
* @param model 模型对象
* @return 返回字典
*/
+ (NSDictionary *)dictionaryWithModel:(id)model; /*!
* @brief 获取Model的所有属性名称
* @param model 模型对象
* @return 返回模型中的所有属性值
*/
+ (NSArray *)propertiesInModel:(id)model; /*!
* @brief 把字典转换成模型,模型类名为className
* @param dict 字典对象
* @param className 类名
* @return 返回数据模型对象
*/
+ (id)modelWithDict:(NSDictionary *)dict className:(NSString *)className; @end
//
// HYBJSONModel.m
// Json2ModelDemo
//
// Created by huangyibiao on 14-9-15.
// Copyright (c) 2014年 Home. All rights reserved.
// #import "HYBJSONModel.h"
#import <objc/runtime.h> typedef NS_ENUM(NSInteger, HYBJSONModelDataType) {
kHYBJSONModelDataTypeObject = ,
kHYBJSONModelDataTypeBOOL = ,
kHYBJSONModelDataTypeInteger = ,
kHYBJSONModelDataTypeFloat = ,
kHYBJSONModelDataTypeDouble = ,
kHYBJSONModelDataTypeLong = ,
}; @implementation HYBJSONModel /*!
* @brief 把对象(Model)转换成字典
* @param model 模型对象
* @return 返回字典
*/
+ (NSDictionary *)dictionaryWithModel:(id)model {
if (model == nil) {
return nil;
} NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // 获取类名/根据类名获取类对象
NSString *className = NSStringFromClass([model class]);
id classObject = objc_getClass([className UTF8String]); // 获取所有属性
unsigned int count = ;
objc_property_t *properties = class_copyPropertyList(classObject, &count); // 遍历所有属性
for (int i = ; i < count; i++) {
// 取得属性
objc_property_t property = properties[i];
// 取得属性名
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
encoding:NSUTF8StringEncoding];
// 取得属性值
id propertyValue = nil;
id valueObject = [model valueForKey:propertyName]; if ([valueObject isKindOfClass:[NSDictionary class]]) {
propertyValue = [NSDictionary dictionaryWithDictionary:valueObject];
} else if ([valueObject isKindOfClass:[NSArray class]]) {
propertyValue = [NSArray arrayWithArray:valueObject];
} else {
propertyValue = [NSString stringWithFormat:@"%@", [model valueForKey:propertyName]];
} [dict setObject:propertyValue forKey:propertyName];
}
return [dict copy];
} /*!
* @brief 获取Model的所有属性名称
* @param model 模型对象
* @return 返回模型中的所有属性值
*/
+ (NSArray *)propertiesInModel:(id)model {
if (model == nil) {
return nil;
} NSMutableArray *propertiesArray = [[NSMutableArray alloc] init]; NSString *className = NSStringFromClass([model class]);
id classObject = objc_getClass([className UTF8String]);
unsigned int count = ;
objc_property_t *properties = class_copyPropertyList(classObject, &count); for (int i = ; i < count; i++) {
// 取得属性名
objc_property_t property = properties[i];
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
encoding:NSUTF8StringEncoding];
[propertiesArray addObject:propertyName];
} return [propertiesArray copy];
} /*!
* @brief 把字典转换成模型,模型类名为className
* @param dict 字典对象
* @param className 类名
* @return 返回数据模型对象
*/
+ (id)modelWithDict:(NSDictionary *)dict className:(NSString *)className {
if (dict == nil || className == nil || className.length == ) {
return nil;
} id model = [[NSClassFromString(className) alloc]init]; // 取得类对象
id classObject = objc_getClass([className UTF8String]); unsigned int count = ;
objc_property_t *properties = class_copyPropertyList(classObject, &count);
Ivar *ivars = class_copyIvarList(classObject, nil); for (int i = ; i < count; i ++) {
// 取得成员名
NSString *memberName = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
const char *type = ivar_getTypeEncoding(ivars[i]);
NSString *dataType = [NSString stringWithCString:type encoding:NSUTF8StringEncoding]; NSLog(@"Data %@ type: %@",memberName,dataType); HYBJSONModelDataType rtype = kHYBJSONModelDataTypeObject;
if ([dataType hasPrefix:@"c"]) {
rtype = kHYBJSONModelDataTypeBOOL;// BOOL
} else if ([dataType hasPrefix:@"i"]) {
rtype = kHYBJSONModelDataTypeInteger;// int
} else if ([dataType hasPrefix:@"f"]) {
rtype = kHYBJSONModelDataTypeFloat;// float
} else if ([dataType hasPrefix:@"d"]) {
rtype = kHYBJSONModelDataTypeDouble; // double
} else if ([dataType hasPrefix:@"l"]) {
rtype = kHYBJSONModelDataTypeLong;// long
} for (int j = ; j < count; j++) {
objc_property_t property = properties[j];
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
encoding:NSUTF8StringEncoding];
NSRange range = [memberName rangeOfString:propertyName]; if (range.location == NSNotFound) {
continue;
} else {
id propertyValue = [dict objectForKey:propertyName]; switch (rtype) {
case kHYBJSONModelDataTypeBOOL: {
BOOL temp = [[NSString stringWithFormat:@"%@", propertyValue] boolValue];
propertyValue = [NSNumber numberWithBool:temp];
}
break;
case kHYBJSONModelDataTypeInteger: {
int temp = [[NSString stringWithFormat:@"%@", propertyValue] intValue];
propertyValue = [NSNumber numberWithInt:temp];
}
break;
case kHYBJSONModelDataTypeFloat: {
float temp = [[NSString stringWithFormat:@"%@", propertyValue] floatValue];
propertyValue = [NSNumber numberWithFloat:temp];
}
break;
case kHYBJSONModelDataTypeDouble: {
double temp = [[NSString stringWithFormat:@"%@", propertyValue] doubleValue];
propertyValue = [NSNumber numberWithDouble:temp];
}
break;
case kHYBJSONModelDataTypeLong: {
long long temp = [[NSString stringWithFormat:@"%@",propertyValue] longLongValue];
propertyValue = [NSNumber numberWithLongLong:temp];
}
break; default:
break;
} [model setValue:propertyValue forKey:memberName];
break;
}
}
}
return model;
} @end
IOS Dictionary和Model相互转换的更多相关文章
- 【AutoMapper官方文档】DTO与Domin Model相互转换(下)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- ios中常用数据类型相互转换
ios中常用数据类型相互转换 //1. NSMutableArray和NSArray互转 // NSArray转为NSMutableArray NSMutableArray *arrM = [arr ...
- 【AutoMapper官方文档】DTO与Domin Model相互转换(上)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- 【AutoMapper官方文档】DTO与Domin Model相互转换(中)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- iOS 字典与JSON相互转换
iOS 字典与JSON相互转换 首先简单说一下为什么会写这种幼稚的文章. 现在的网络请求几乎都是AFN完成的,AFN也为我们写了了JSON转换字典的方法,但是不要忘记后台是一个很爱用JSON的人群,H ...
- iOS标准时间与时间戳相互转换
iOS标准时间与时间戳相互转换 (2012-07-18 17:03:34) 转载▼ 标签: ios 时间戳 标准时间 格式 设置 转化 杂谈 分类: iPhone开发 设置时间显示格式: NS ...
- 判断iOS系统的Model
获取iOS系统的Model (参考网址:https://www.theiphonewiki.com/wiki/Models) + (NSString *)getModel{ struct utsn ...
- C# 类型转换 Dictionary转Model类
/// <summary> /// 把Model转换为DataRow /// </summary> /// <typeparam name="T"&g ...
- Dictionary转为Model实例
Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add(); dic.Add(&q ...
随机推荐
- 面试小结(java基础)
一个.java源文件中可以有多个类吗?(内部类除外)有什么条件?带着这个疑惑,动手建几个测试类, 揭开心中的疑惑.以下是解开疑惑过程: package test;/** * 一个.java源文件中可以 ...
- PHPCMS收集标签使用
调用子栏目(在栏目首页模板需要用到) {pc:content action="category" catid="$catid" num="25&quo ...
- VC++ 列表控件的使用方法
列表控件可以看作是功能增强的ListBox,它提供了四种风格,而且可以同时显示一列的多中属性值.MFC中使用CListCtrl类来封装列表控件的各种操作. 通过调用BOOL Create( DWORD ...
- Eclipse 代码自动补全
使用Eclipse开发Android时,发现代码补全功能太差,完全不像VS似的,输入一个字母就出现代码提示. 下面是在Eclipse中实现类似VS代码补全的方法: ①打开Eclipse->Win ...
- call stack 如何调用
现在在处理MFC上面的BUG,比较多,刚接触堆债,自我感觉找BUG很好用,总结一下记下来: 1. VS环境在程序F5运行状态下/DEBUG/Windows/Call Stack 即可调用堆债: 2. ...
- tomcat源码阅读
1 工具准备 需要SVN.Maven.JDK.Eclipse.Eclipse M2插件 2 下载源码及发布包 源码在这里:http://svn.apache.org/repos/a ...
- 试玩GitHub
SVN是可以,但GitHub越来越屌啊... SO...要玩起来.. 参考URL: http://jingyan.baidu.com/article/f7ff0bfc7181492e27bb1360. ...
- DB2中SQLSTATE=57016 SQLCODE=-668
执行 alter table DW_RPT.TRPT_JV_COGNOS_RPT add CENTER_CD varchar(10) ALTER TABLE DW_RPT.TRPT_JV_COGNOS ...
- struts2+jquery+json集成
以下采用struts2+jquery+json模拟一个案例.当点击提交按钮时会把输入的数据提交到后台,然后从后台获取数据在客户端显示. 效果如下: 接下来为struts2+jquery+json集成步 ...
- [转载][HTML] 普通的DIV分层以及版透明效果
来源忘记哪的了,我稍微做了点修改,想了想还是挂了转载的标签,嗯嗯: <html> <head> <title>EXAMPLE</title> </ ...