Objective-C Json to Model (using the Runtime feature)

Encapsulate the initWithNSDictionary: method

This method receives an NSDictionary object and returns a PersonModel object.

 #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);    }}

Implementation using runtime

The header file of PersonModel is as follows:

 #import 

Implementation file:

#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

The code in it is also very simple:

Use class_copyPropertyList to get a list of all properties of the Model, traverse the list and use property_getName to get all the property names.
For properties defined in PersonModel, use KVC to assign the value in dict to the property.#

Reprinted from: [id]: https://blog.csdn.net/icetime17/article/details/52040301

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324911346&siteId=291194637