• 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    = 0,
        kHYBJSONModelDataTypeBOOL      = 1,
        kHYBJSONModelDataTypeInteger   = 2,
        kHYBJSONModelDataTypeFloat     = 3,
        kHYBJSONModelDataTypeDouble    = 4,
        kHYBJSONModelDataTypeLong      = 5,
    };
    
    @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 = 0;
        objc_property_t *properties = class_copyPropertyList(classObject, &count);
        
        // 遍历所有属性
        for (int i = 0; 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 = 0;
        objc_property_t *properties = class_copyPropertyList(classObject, &count);
        
        for (int i = 0; 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 == 0) {
            return nil;
        }
        
        id model = [[NSClassFromString(className) alloc]init];
        
        // 取得类对象
        id classObject = objc_getClass([className UTF8String]);
        
        unsigned int count = 0;
        objc_property_t *properties = class_copyPropertyList(classObject, &count);
        Ivar *ivars = class_copyIvarList(classObject, nil);
    
        for (int i = 0; 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 = 0; 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
  • 相关阅读:
    对话框中获取Month Calendar的当前日期
    JAVA GUI程序示例
    MFC控件显示值和控件变量值的更新
    JAVA求10到99的随机数
    学习之路二:关于集合和数组内在联系的深入了解
    迭代器学习之三:IEnumerable和IEnumerator的泛型结构
    迭代器学习之四:关于yield的深入了解
    迭代器学习之二:数组的可枚举类型和枚举数的定义以及编译器的foreach工作原理
    学习之路三:关于运用单线程和委托以及事件自定义Timer类
    迭代器学习之一:使用IEnumerable和IEnumerator接口
  • 原文地址:https://www.cnblogs.com/enya1999/p/4260561.html
Copyright © 2020-2023  润新知