iOS --- 使用runtime将JSON转换成Model

本文介绍了一种使用Objective-C运行时API将JSON数据转换为模型对象的方法。通过封装initWithNSDictionary:方法,可以方便地将从JSON文件中解析出的数据映射到自定义的PersonModel对象上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里简单介绍如何使用runtime将JSON转换成Model.

封装initWithNSDictionary:方法

该方法接收NSDictionary对象, 返回PersonModel对象.

#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中的值赋给该属性.

Demo

Demo请参考:
iOS-RuntimeDemo.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值