//
// 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相互转换的更多相关文章

  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. HTML 动态显示系统当前时间

    HTML 动态显示系统当前时间: <div id="time"> <script> document.getElementById('time').inne ...

  2. 原生Js获取某个节点后面的第一个标签

    nextSlbling属性 获取某个节点后面的第一个节点(可能是标签 文本) 判断获取的节点是否为标签节点还是文本节点 window.onload=function(){ var pagecount= ...

  3. nginx 编译选项

    内容有些多,一眼看来难免头昏脑胀,但坚持看完,相信你一定会有所收获. nginx参数: --prefix= 指向安装目录 --sbin-path 指向(执行)程序文件(nginx) --conf-pa ...

  4. 基于 Webpack & Vue & Vue-Router 的 SPA 初体验

    基于 Webpack & Vue & Vue-Router 的 SPA 初体验 本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com ...

  5. Java 中 Comparable 和 Comparator 比较(转)

    转自http://www.cnblogs.com/skywang12345/p/3324788.html 本文,先介绍Comparable 和Comparator两个接口,以及它们的差异:接着,通过示 ...

  6. C++例题2:汉诺塔问题

    #include<iostream>#include<stdlib.h>using namespace std;void Hanoi(int n,char A,char B,c ...

  7. ubuntu wubi安装注意事项

    从这个镜像下载 http://mirrors.163.com/ubuntu-releases/12.10/ ubuntu-12.10-desktop-amd64.iso 和 wubi.exe然后放到同 ...

  8. sql server更改机器名后更改数据库机器名

    方式一: 本地机器名查询: select * from sys.servers 修改机器名: sp_dropserver 'old server name' sp_addserver 'new ser ...

  9. BAT互联网公司是如何内部推荐的?

    中国十大互联网公司 注:以上按照目前市值排序整理出来,当然还有更多未上市的潜力股.如:美团.豆瓣.豌豆荚.美图秀秀等等 各大互联网公司招聘官网 阿里招聘:https://job.alibaba.com ...

  10. 可重入与线程安全(大多数Qt类是可重入,非线程安全的)

    可重入与线程安全 在Qt文档中,术语“可重入”与“线程安全”被用来说明一个函数如何用于多线程程序.假如一个类的任何函数在此类的多个不同的实例上,可以被多个线程同时调用,那么这个类被称为是“可重入”的. ...