• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Objective-C Json转Model(利用Runtime特性)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

封装initWithNSDictionary:方法###

#pragma mark - 使用runtime将JSON转成Model
- (void)json2Model {
   `NSString *file = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"json"];`
    NSData *data = [NSData dataWithContentsOfFile:file];
    NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    for (NSDictionary *model in array) {
        PersonModel *person = [[PersonModel alloc] initWithNSDictionary:model];
        NSLog(@"%@, %ld, %@, %@", person.name, (long)person.age, person.city, person.job);
    }
}

使用runtime实现###

PersonModel的头文件如下:#

#import <Foundation/Foundation.h>
@interface PersonModel : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *job;

- (instancetype)initWithNSDictionary:(NSDictionary *)dict;

@end

实现文件:

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

@implementation PersonModel

- (instancetype)initWithNSDictionary:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        [self prepareModel:dict];
    }
    return self;
}

- (void)prepareModel:(NSDictionary *)dict {
    NSMutableArray *keys = [[NSMutableArray alloc] init];

    u_int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = properties[i];
        const char *propertyCString = property_getName(property);
        NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    free(properties);

    for (NSString *key in keys) {
        if ([dict valueForKey:key]) {
            [self setValue:[dict valueForKey:key] forKey:key];
        }
    }
}

@end

其中的代码也很简单:

使用class_copyPropertyList获取Model的所有属性列表, 遍历该列表使用property_getName即可得到所有属性名. 
对于PersonModel中定义的属性, 使用KVC即可将dict中的值赋给该属性.

转自:[id]:https://blog.csdn.net/icetime17/article/details/52040301


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Objective-C Runtime 运行时之五:协议与分类发布时间:2022-07-12
下一篇:
学习OBJECTIVE C真的那么难以忍受吗?发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap