iOS MJExtension的使用

前言:

MJExtension是iOS的字典装模型的一个第三方框架。相对于JSONKit和SBJson相比MJExtension更简单易用、功能更强大。

安装:

使用CocoaPods导入(CocoaPods的使用方法在其他文档里面会介绍)

pod 'MJExtension'

在使用该框架的文件里面导入头文件(推荐在pch文件中导入)

#import "MJExtension.h"

格式单一的字典(没有嵌套),转模型:

@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *sex;
@property (copy, nonatomic) NSString *age;
@end
NSDictionary *dict = @{
    @"name" : @"Jack",
    @"sex" : @"男",
    @"age" : @"20"
}

User *UserModel = [User Mj_objectWithKeyValues:dict];

字典嵌套字典:

@interface People : NSObject
@property (copy, nonatomic) User *User;(上面的User类)
@property (copy, nonatomic) NSString *height;
@property (copy, nonatomic) NSString *wight;
@end

NSDictionary *dict = @{
   @"height":@"170"
@"wight":@"70"
@"user":@{
@"name" : @"Jack",
@"sex" : @"男",
@"age" : @"20"

}
}
Poeple *peopleModel = [Pople mj_objectWithKeyValues:dict];

字典嵌套数组,数组里面还有字典:

@interface People : NSObject
@property (copy, nonatomic) NSarray  *UserArr;(上面的User类)
@property (copy, nonatomic) NSString *height_2;
@property (copy, nonatomic) NSString *wight;
@end

  @implementation People

 

  

   +(NSDictionary *)mj_objectClassInArray//模型中数组里面的模型

   { 

     return @{

             @"UserArr":@"User",//UserArr是自定义的属性名,User是嵌套的字典类名

             };

   }

 

+(NSDictionary *)mj_replacedKeyFromPropertyName

{

    return @{

             @"UserArr":@"User",//模型和字典的字段不对应需要转化

             };

}

   @end



NSDictionary *dict = @{
   @"height":@"170"
@"wight":@"70"
@"UserArr":@[
@{

@"name" : @"Jack",

@"sex" : @"男",
                        @"age" : @"20"
                  },
                  @{
                        @"name" : @"li",
@"sex" : @"女",
@"age" : @"30"
}
                 ]
}

People *people = [People mj_objectWithKeysValues:dict];

数组转化成模型数组

NSArray *arr = @[
@{
@"name":@"Jack",
@"sex":@"男",
@"age":@"25"
}
@{
@"name":@@"wang",
@"sex":@"男",
@"age":@"26"
}
]
NSArray *UserArrModel = [User mj_objectArrayWithValuesArray:arr];

 

GitHub地址 https://github.com/CoderMJLee/MJExtension

posted @ 2019-02-22 10:47  hello_小磊  阅读(1061)  评论(0编辑  收藏  举报