分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

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

发布时间:2023-09-06 01:51责任编辑:彭小芳关键词:暂无标签

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

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

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

原文地址:https://www.cnblogs.com/codeSnail/p/8944549.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved