【iOS开发】MJExtension的使用

  • JSONModel
NSDictionary *dict = @{@"name" : @"黄堡钦", @"address" : @"洪文六里"};
HBQUser *user = [HBQUser mj_objectWithKeyValues:dict];
NSLog(@"\n name = %@ \n address = %@\n", user.name, user.address);
image
  • JSONStringModel
NSString *jsonString = @"{\"name\":\"黄堡钦\", \"address\":\"洪文六里\"}";
HBQUser *user = [HBQUser mj_objectWithKeyValues:jsonString];
NSLog(@"\n name = %@ \n address = %@\n", user.name, user.address);
image
  • Model 中包含其他 Model
NSDictionary *dict = @{@"name" : @"X", @"firstUser" : @{@"name" : @"黄堡钦", @"address" : @"洪文六里"}};
HBQCompany *company = [HBQCompany mj_objectWithKeyValues:dict];
NSLog(@"\n company.name = %@ \n company.firstUser = %@ \n", company.name, company.firstUser);
image
  • Model 中包含 Model 数组
NSDictionary *dict = @{@"name" : @"X", @"firstUser" : @{@"name" : @"黄堡钦", @"address" : @"洪文六里"}, @"users" : @[@{@"name" : @"王五", @"address" : @"洪文六里"}, @{@"name" : @"李四", @"address" : @"洪文六里"}, @{@"name" : @"张三", @"address" : @"洪文六里"}]};
HBQCompany *company = [HBQCompany mj_objectWithKeyValues:dict];
NSLog(@"\n company.name = %@ \n company.firstUser = %@ \n company.users = %@ \n", company.name, company.firstUser, company.users);
#import "HBQCompany.h"

@implementation HBQCompany

+ (NSDictionary *)mj_objectClassInArray {
    return @{
             @"users" : @"HBQUser"
             };
}

@end
image
  • Model 属性名JSON 的 Key 的映射(或者多级映射)
// 将 Model 中的 name 改成 NAME 到字典中取值,也能将 name 映射到字典的更深层级用点语表示
+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{
             @"name" : @"NAME",
             @"address" : @"ADDRESS"
             };
}
  • JSON 数组Model 数组
NSArray *users = @[@{@"name" : @"黄堡钦1", @"address" : @"洪文六里"}, @{@"name" : @"黄堡钦2", @"address" : @"洪文六里"}, @{@"name" : @"黄堡钦3", @"address" : @"洪文六里"}, @{@"name" : @"黄堡钦4", @"address" : @"洪文六里"}, @{@"name" : @"黄堡钦5", @"address" : @"洪文六里"}];
NSArray *userArray = [HBQUser mj_objectArrayWithKeyValuesArray:users];
NSLog(@"%@", userArray);
  • ModelJSON
HBQUser *user = [[HBQUser alloc] init];
user.name = @"黄堡钦";
user.address = @"洪文六里";
NSDictionary *userDict = [user mj_keyValues];
NSLog(@"%@", userDict);
  • Model 数组JSON 数组
NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
  • NSStringNSDate ,nil@""
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property {
    if ([property.name isEqualToString:@"publisher"]) {
        if (oldValue == nil) return @"";
    } else if (property.type.typeClass == [NSDate class]) {
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        return [fmt dateFromString:oldValue];
    }
    return oldValue;
}

你可能感兴趣的:(【iOS开发】MJExtension的使用)