JSON与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


目录
相关文章
|
4月前
|
JSON fastjson Java
(fastjson)java 如何将String(字符串)与JSON互转
(fastjson)java 如何将String(字符串)与JSON互转
74 1
|
5月前
|
JSON 数据格式 Python
Python将字符串(str/json)和字典(dict)互转
Python将字符串(str/json)和字典(dict)互转
|
5月前
|
JSON 数据格式
JSON字符串与Map互转
JSON字符串与Map互转
|
6月前
|
JSON C语言 数据格式
使用cJSON库实现JSON与C结构体的互转
在实际应用中,我们经常需要将JSON格式的数据与C语言中的结构体进行相互转换。cJSON是一个非常便捷的C语言JSON解析库,它可以帮助我们在C语言中轻松地处理JSON数据。本文将介绍如何使用cJSON库来实现JSON数据与C结构体的互转。
261 2
|
9月前
|
JSON 数据格式
UE4 结构体和JSON互转 - DTBPJson插件说明
UE4 结构体和JSON互转 - DTBPJson插件说明
211 1
|
10月前
|
JSON 自然语言处理 监控
使用go-zero微服务框架实现云监控后台(三.c语言操作cJson封装,json和结构体互转)
使用go-zero微服务框架实现云监控后台(三.c语言操作cJson封装,json和结构体互转)
|
JSON 数据格式
JSON工具类 转对象,数组,集合,JSON互转
JSON工具类 转对象,数组,集合,JSON互转
204 0
|
JSON Dart 数据格式
dart中json和对象互转
开发过程中,json是必不可少的基础技能之一。这里记录下,在Dart语言中,如何将json解析成实例对象,以及如何将实例对象转化成json字符串。
|
JSON 安全 数据格式
YYModel JSON和model相互转化
JSON转模型是我们做iOS开发的基础技能,本文将通过[YYModel](https://github.com/ibireme/YYModel)这个框架安全快速的完成JSON到模型的转换,其中还会介绍到一款好用的插件[ESJsonFormat](https://github.com/EnjoySR/ESJsonFormat-Xcode)。
547 0
|
JSON Dart Android开发
Flutter如何JSON转Model
在开发中,服务端通常给我们返回的是JSON数据,我们需要将JSON数据转成我们的模型对象来使用。 在Flutter中,有几种JSON转模型的方式,我们还是以豆瓣为例,来进行一个演练;
630 0
Flutter如何JSON转Model