//
// 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. jQuery判断文本框是否为空

    1.引用jQuery库 <script src="/static/js/jquery_v1.6.1.js" type="text/javascript"& ...

  2. [转] 翻译-高质量JavaScript代码书写基本要点 ---张鑫旭

    by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=1173 原文作者:St ...

  3. C#中静态方法和非静态方法的区别(二)

    一.引言 在C#中,静态和非静态的特征对于我们来说是再熟悉不过了,但是很少看到有一篇文章去好好地总结静态和非静态它们之间的不同,为了帮助大家更好地去理解静态和非静态特征, 所以将在这篇文章中帮大家全面 ...

  4. E: Some packages could not be authenticated

    问题:          在Ubuntu上,安装软件时出现了“E: Some packages could not be authenticated”错误. 原因:     表示系统无法验证这个软件包 ...

  5. 将日志写入EventLog

    将日志写入EventLog 面向Windows的编程人员应该不会对Event Log感到陌生,以至于很多人提到日志,首先想到的就是EventLog.EventLog不仅仅记录了Windows系统自身针 ...

  6. 【译】UI设计基础(UI Design Basics)--为iOS设计(Design for iOS)(二)

    2.1 为iOS设计(Design for iOS) iOS体现以下主题: 遵从:UI帮助用户理解界面内容并与内容交互,但绝不会与内容相互冲突. 清晰:文本在任何尺寸下都是清晰易读,图标精确易懂,装饰 ...

  7. core dump

    Core Dump?! 整理:Wilbur Lang 何谓 core? 在使用半导体作为内存的材料前,人类是利用线圈当作内存的材料(发明 者为王安),线圈就叫作 core ,用线圈做的内存就叫作 co ...

  8. 【转】Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例

    原文网址:http://www.cnblogs.com/skywang12345/p/3308556.html 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具 ...

  9. Android Studio导入Eclipse项目

    随着Google 对新Android编辑器Android Studio(以下简称AS)的版本不断更新,越来越多的人开始由熟悉的编辑器Eclipse转向AS,而Eclipse开发团队也坦言将放弃对Ecl ...

  10. 字符串(后缀自动机):COGS 2399. 循环同构

    这道题直接看代码吧. #include <iostream> #include <cstring> #include <cstdio> using namespac ...