将json数据映射到本地数据模型对象的一点想法

在日常的开发中我们经常遇到的一种情况就是把从服务端请求回来的数据(此处暂且就当做是json的数据格式)映射成本地数据模型的对象。如果一个对象一个对象的去初始化,势必很浪费时间,这里是自己总结的一点想法:运用iOS的强大的运行时(runtime)来对这项工作做一个较统一的处理,废话不多说直接上代码。


1、首先声明一个基类PHObject代码如下

PHObject.h

@interface PHObject : NSObject<NSCopying,NSCoding>

// 解析API返回的JSON,返回对应的Model
- (id)initWithDictionary:(NSDictionary *)JSON;

// JSON key到property的映射关系(支持字典嵌套)
- (NSDictionary *)JSONKeysToPropertyKeys;

// JSON key到 array property的映射关系
- (NSDictionary *)JSONKeysToArrayPropertyKeys;

PHObject.m( 此处尚未实现NSCopying和NSCoding协议

//https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html

#import "PHObject.h"
#import <objc/runtime.h>


@implementation PHObject

// 解析API返回的JSON,返回对应的Model对象
- (id)initWithDictionary:(NSDictionary *)JSON{
    if(self = [super init]){
        [JSON enumerateKeysAndObjectsUsingBlock:^(id JSONKey,id JSONObj ,BOOL *stop){
            NSString* propertyKey = [self JSONKeysToPropertyKeys][JSONKey];
            propertyKey = propertyKey ? propertyKey : JSONKey;
            Class classOfProperty = [self propertyClassFromClass:[self class]
                                                  forPropertyKey:propertyKey];
            if(classOfProperty != NULL){
                id propertyValue = nil;
                if([classOfProperty isSubclassOfClass:[PHObject class]] &&
                   [JSONObj isKindOfClass:[NSDictionary class]]){
                    propertyValue = [
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值