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

Posted snail_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Objective-C Json转Model(利用Runtime特性)相关的知识,希望对你有一定的参考价值。

封装initWithNSDictionary:方法

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

#pragma mark - 使用runtime将JSON转成Model

@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特性)的主要内容,如果未能解决你的问题,请参考以下文章

MVC之Model转Json

Flutter json 2 model with Built Value

C# Json 转 Model / Model 转 Json

如何将json转成对应的model

[Flutter] 08-Flutter中的Json转Model

Django JSON与Model互转