1、简单的字典转模型
- (void)viewDidLoad {
[super viewDidLoad];
[self test5];
}
- (void)test5 {
NSDictionary *json = @{
@"age": @20,
@"weight": @60,
@"name": @"Jack"
};
Person *person = [[Person alloc] init];
person.age = [json[@"age"] intValue];
person.weight = [json[@"weight"] intValue];
person.name = json[@"name"];
NSLog(@"-");
}
2、runtime的API封装方法
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (Json)
+ (instancetype)jh_objectWithJson:(NSDictionary *)json;
@end
NS_ASSUME_NONNULL_END
#import "NSObject+Json.h"
#import <objc/runtime.h>
@implementation NSObject (Json)
+ (instancetype)jh_objectWithJson:(NSDictionary *)json {
id obj = [[self alloc] init];
unsigned int count;
Ivar *ivars = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
NSMutableString *name = [NSMutableString stringWithUTF8String:ivar_getName(ivar)];
[name deleteCharactersInRange:NSMakeRange(0, 1)];
[obj setValue:json[name] forKey:name];
}
free(ivars);
return obj;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
[self test6];
}
- (void)test6 {
NSDictionary *json = @{
@"age": @20,
@"weight": @60,
@"name": @"Jack"
};
Person *person = [Person jh_objectWithJson:json];
NSLog(@"--");
}