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 ...
随机推荐
- html 标签的嵌套规则
1. 块元素可以包含内联元素或某些块元素,但内联元素却不能包含块元素,它只能包含其它的内联元素: <div><h1></h1><p></p> ...
- windows下搭建PHP环境
1.Apache 下载地址:http://httpd.apache.org/download.cgi 下载之后进入CMD,/Apache/bin/httpd.exe -k install 进行安装 提 ...
- 转:php的memcache和memcached扩展区别
原文来自于:http://www.cnblogs.com/yjf512/p/3778287.html 作者:叶剑峰 老生长谈的问题了.我这里就整理一下. memcache的文档在:http://pec ...
- 转:aptitude 命令详解
原文:http://www.isspy.com/aptitude-%E5%91%BD%E4%BB%A4%E8%AF%A6%E8%A7%A3/ aptitude aptitude 是 Debian GN ...
- 【深入浅出jQuery】源码浅析2--使用技巧
最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...
- BZOJ 1563 诗人小G
Description Input Output 对于每组数据,若最小的不协调度不超过\(10^{18}\),则第一行一个数表示不协调度若最小的不协调度超过\(10^{18}\),则输出"\ ...
- java 对象序列化 RMI
对于一个存在于Java虚拟机中的对象来说,其内部的状态只保持在内存中.JVM停止之后,这些状态就丢失了.在很多情况下,对象的内部状态是需要被持久化下来的.提到持久化,最直接的做法是保存到文件系统或是数 ...
- Polyfills
填充物..github上比较全的列表 IE总是有填不完的坑,在此总结一下,可能暂时都是一知半解,错了我会慢慢改的. 首先html5标签需要填充一些class,可以用html5.js处理,或者html5 ...
- 【HDOJ】5128
暴力+计算几何. /* 5128 */ #include <iostream> #include <algorithm> #include <cstdio> #in ...
- poj2594
特殊的最小路径覆盖回顾一下经典的最小路径覆盖问题是每个点都恰好被一条路径覆盖我们把有向无环图的点拆成i,i',对于原图中边i--->j,连边i-->j'做最大匹配,答案是原图点数-最大匹配 ...