jsonkit 和jsonkit mjextensionn 会冲突吗

MJExtension使用指导(转) - 简书
下载简书移动应用
写了24692字,被289人关注,获得了188个喜欢
MJExtension使用指导(转)
当自己看到原文的排版时,真的是。。。,自己花了点时间重新排版了下,分享出来!原文链接:
MJExtension能做什么?
MJExtension是一套字典和模型之间互相转换的超轻量级框架
MJExtension能完成的功能
字典(JSON) --& 模型(Model)
模型(Model) --& 字典(JSON)
字典数组(JSON Array) --& 模型数组(Model Array)
模型数组(Model Array) --& 字典数组(JSON Array)
详尽用法主要参考 main.m中的各个函数 以及 NSObject+MJKeyValue.h
MJExtension和JSONModel、Mantle等框架的区别
1. 转换速率:
最近一次测试表明:MJExtension & JSONModel & Mantle
各位开发者也可以自行测试
2.具体用法:
JSONModel:
要求所有模型类必须继承自JSONModel基类
要求所有模型类必须继承自MTModel基类
MJExtension:
不需要你的模型类继承任何特殊基类,毫无污染,毫无侵入性
如何使用MJExtension
方法一:cocoapods导入:pod 'MJExtension'
方法二:手动导入:
将MJExtensionExample/MJExtensionExample/MJExtension文件夹中的所有源代码拽入项目中
导入主头文件:#import "MJExtension.h"
MJExtension.h
MJFoundation.h
MJFoundation.m
NSObject+MJCoding.h
NSObject+MJCoding.m
NSObject+MJIvar.h
NSObject+MJIvar.m
NSObject+MJKeyValue.h
NSObject+MJKeyValue.m
1.最简单的字典转模型
typedef enum {
SexFemale} S
@interface User : NSObject
@property (copy, nonatomic) NSString *
@property (copy, nonatomic) NSString *
@property (assign, nonatomic)
@property (assign, nonatomic)
@property (strong, nonatomic) NSNumber *
@property (assign, nonatomic) S
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @20,
@"height" : @"1.55",
@"money" : @100.9,
@"sex" : @(SexFemale)
// 将字典转为User模型
User *user = [User objectWithKeyValues:dict];
NSLog(@"name=%@, icon=%@, age=%d, height=%@, money=%@, sex=%d", user.name, user.icon, user.age, user.height, user.money, user.sex);
// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1
核心代码1:
[User objectWithKeyValues:dict]
2.模型中嵌套模型
@interface Status : NSObject
/** 微博文本内容 */
@property (copy, nonatomic) NSString *
/** 微博作者 */
@property (strong, nonatomic) User *
/** 转发的微博 */
@property (strong, nonatomic) Status *retweetedS
NSDictionary *dict = @{
@"text" : @"是啊,今天天气确实不错!",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
@"retweetedStatus" : @{
@"text" : @"今天天气真不错!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
// 将字典转为Status模型
Status *status = [Status objectWithKeyValues:dict];
NSString *text = status.
NSString *name = status.user.
NSString *icon = status.user.
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=是啊,今天天气确实不错!, name=Jack, icon=lufy.png
NSString *text2 = status.retweetedStatus.
NSString *name2 = status.retweetedStatus.user.
NSString *icon2 = status.retweetedStatus.user.
NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
// text2=今天天气真不错!, name2=Rose, icon2=nami.png
[Status objectWithKeyValues:dict]
3.模型中有个数组属性,数组里面又要装着其它模型
@interface Ad : NSObject
@property (copy, nonatomic) NSString *
@property (copy, nonatomic) NSString *
@interface StatusResult : NSObject
/** 存放着一堆的微博数据(里面都是Status模型) */
@property (strong, nonatomic) NSMutableArray *
/** 存放着一堆的广告数据(里面都是Ad模型) */
@property (strong, nonatomic) NSArray *
@property (strong, nonatomic) NSNumber *totalN
@implementation StatusResult
// 实现这个方法的目的:告诉MJExtension框架statuses和ads数组里面装的是什么模型
+ (NSDictionary *)objectClassInArray{
@"statuses" : [Status class],
@"ads" : [Ad class]
+ (Class)objectClassInArray:(NSString *)propertyName{
if ([propertyName isEqualToString:@"statuses"]) {
return [Status class];
} else if ([propertyName isEqualToString:@"ads"]) {
return [Ad class];
// 这个方法对比上面的2个方法更加没有侵入性和污染,因为不需要导入Status和Ad的头文件
+ (NSDictionary *)objectClassInArray{
@"statuses" : @"Status",
@"ads" : @"Ad"
NSDictionary *dict = @{
@"statuses" : @[
@"text" : @"今天天气真不错!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
@"text" : @"明天去旅游了",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
@"ads" :@[
@"image" : @"ad01.png",
@"url" : @""
@"image" : @"ad02.png",
@"url" : @""
@"totalNumber" : @"2014"
// 将字典转为StatusResult模型
StatusResult *result = [StatusResult objectWithKeyValues:dict];
NSLog(@"totalNumber=%@", result.totalNumber);
// totalNumber=2014
// 打印statuses数组中的模型属性
for (Status *status in result.statuses) {
NSString *text = status.
NSString *name = status.user.
NSString *icon = status.user.
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);}
// text=今天天气真不错!, name=Rose, icon=nami.png
// text=明天去旅游了, name=Jack, icon=lufy.png
// 打印ads数组中的模型属性
for (Ad *ad in result.ads) {
NSLog(@"image=%@, url=%@", ad.image, ad.url);}
// image=ad01.png, url=
// image=ad02.png, url=
核心代码3:
在模型内部实现+ (NSDictionary *)objectClassInArray方法
[StatusResult objectWithKeyValues:dict]
4.模型中的属性名和字典中的key不相同(或者需要多级映射)
@interface Bag : NSObject
@property (copy, nonatomic) NSString *
@property (assign, nonatomic)@end@interface Student : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *
@property (copy, nonatomic) NSString *nowN
@property (copy, nonatomic) NSString *oldN
@property (copy, nonatomic) NSString *nameChangedT
@property (strong, nonatomic) Bag *
@implementation Student
// 实现这个方法的目的:告诉MJExtension框架模型中的属性名对应着字典的哪个key
+ (NSDictionary *)replacedKeyFromPropertyName{
@"ID" : @"id",
@"desc" : @"desciption",
@"oldName" : @"name.oldName",
@"nowName" : @"name.newName",
@"nameChangedTime" : @".nameChangedTime",
@"bag" : @"other.bag"
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"孩子",
@"name" : @{
@"newName" : @"lufy",
@"oldName" : @"kitty",
@"info" : @{
@"nameChangedTime" : @"2013-08"
@"other" : @{
@"bag" : @{
@"name" : @"小书包",
@"price" : @100.7
// 将字典转为Student模型
Student *stu = [Student objectWithKeyValues:dict];
// 打印Student模型的属性
NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@", stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);
// ID=20, desc=孩子, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
// bagName=小书包, bagPrice=100.700000
核心代码4:
在模型内部实现+ (NSDictionary *)replacedKeyFromPropertyName方法
[Student objectWithKeyValues:dict]
5.将一个字典数组转成模型数组
NSArray *dictArray = @[
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"name" : @"Rose",
@"icon" : @"nami.png",
// 将字典数组转为User模型数组
NSArray *userArray = [User objectArrayWithKeyValuesArray:dictArray];
// 打印userArray数组中的User模型属性
for (User *user in userArray) {
NSLog(@"name=%@, icon=%@", user.name, user.icon);}
// name=Jack, icon=lufy.png
// name=Rose, icon=nami.png
核心代码5:
[User objectArrayWithKeyValuesArray:dictArray]
6.将一个模型转成字典
// 新建模型
User *user = [[User alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";
Status *status = [[Status alloc] init];
status.user =
status.text = @"今天的心情不错!";
// 将模型转为字典
NSDictionary *statusDict = status.keyV
NSLog(@"%@", statusDict);
/*{ text = "今天的心情不错!";
icon = "lufy.png";
// 多级映射的模型
Student *stu = [[Student alloc] init];
stu.ID = @"123";
stu.oldName = @"rose";
stu.nowName = @"jack";
stu.desc = @"handsome";
stu.nameChangedTime = @"";
Bag *bag = [[Bag alloc] init];
bag.name = @"小书包";
bag.price = 205;
NSDictionary *stuDict = stu.keyVNSLog(@"%@", stuDict);
desciption =
nameChangedTime = "";
name = "小书包";
price = 205;
核心代码6:
status.keyValues、stu.keyValues
7.将一个模型数组转成字典数组
// 新建模型数组
User *user1 = [[User alloc] init];
user1.name = @"Jack";
user1.icon = @"lufy.png";
User *user2 = [[User alloc] init];
user2.name = @"Rose";
user2.icon = @"nami.png";
NSArray *userArray = @[user1, user2];
// 将模型数组转为字典数组
NSArray *dictArray = [User keyValuesArrayWithObjectArray:userArray];
NSLog(@"%@", dictArray);
icon = "lufy.png";
icon = "nami.png";
核心代码7:
[User keyValuesArrayWithObjectArray:userArray]
参考NSObject+MJKeyValue.h
参考NSObject+MJCoding.h
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮
被以下专题收入,发现更多相似内容:
收集进阶知识、编程干货
,每天会更新四篇。对于接收的文章,伯乐在线(@iOS大全)小编会联系您进行转载推广。如果您的投稿没有通过,可...
· 945人关注
不定期更新iOS技术知识点、总结归纳、整理开发技巧,相互学习,共同进步!
【进一步交流学习】
个人博客:ht...
· 146人关注
· 19人关注
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
选择支付方式:10676人阅读
IOS大神之路(15)
MJExtension很强大,几乎支持现有所有的模型、字典、json数据转换,而且效率非常高
以前写对象归档的时候,需要让这个对象实现NSCoding协议,而且要对每一个需要归档的属性做一些encode和decode操作,例如你之前的代码可能是这样子的
Person.h文件
#import "Person.h"
@interface Person : NSObject &NSCoding&
@property (nonatomic,copy) NSString *
@property (nonatomic,assign) int
@property (nonatomic,assign) BOOL
Person.m文件
#import "Person.h"
@implementation Person
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
NSNumber *at = [aDecoder decodeObjectForKey:@"age"];
self.age = at.intValue ;
NSNumber *isgay = [aDecoder decodeObjectForKey:@"gay"];
self.gay = isgay.intValue;
return self;
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:[NSNumber numberWithInt:self.age] forKey:@"age"];
[aCoder encodeObject:[NSNumber numberWithInt:self.gay] forKey:@"gay"];
这需要重写initWithCoder和encodeWithCoder这两个方法,比较繁琐,这和Android里面的实现Parcelable差不多,要写一大堆的代码,不过Android有解决这个问题的方案,通过安装AndroidStudio插件来解决,请看前面讲的这篇文章,其实,IOS里面也有相关的解决方案,而且比Android实现更简单,快速和高效,一句代码搞定,不信?之前我也不信,但是当我看到MJExtension之后,我就信了!
MJExtension非常好用但是容易被忽略的功能:不管你的模型属性有几百个,只需要加一句宏MJCodingImplementation,就能实现归档解档,不用再编写恶心的encodeWithCoder:和initWithCoder:了
代码示例如下,Person.h代码不变,只需要将Person.m文件内容改成下面的就OK了:
#import "Person.h"
#import "MJExtension.h"
@implementation Person
MJCodingImplementation
搞定,啥玩意,这样写就实现了?不是坑人的吧,肯定不是喽,其实归档和反归档代码本质上都要写,只不过MJExtension帮我们做了,我们去点击这个MJCodingImplementation去看看,发现代码是这样的:
#import &Foundation/Foundation.h&
@interface NSObject (MJCoding)
解码(从文件中解析对象)
- (void)decode:(NSCoder *)
编码(将对象写入文件中)
- (void)encode:(NSCoder *)
归档的实现
#define MJCodingImplementation \
- (id)initWithCoder:(NSCoder *)decoder \
if (self = [super init]) { \
[self decode:decoder]; \
- (void)encodeWithCoder:(NSCoder *)encoder \
[self encode:encoder]; \
再看实现类代码
#import "NSObject+MJCoding.h"
#import "NSObject+MJMember.h"
@implementation NSObject (MJCoding)
编码(将对象写入文件中)
- (void)encode:(NSCoder *)encoder
[self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
if (ivar.isSrcClassFromFoundation) return;
[encoder encodeObject:ivar.value forKey:ivar.name];
解码(从文件中解析对象)
- (void)decode:(NSCoder *)decoder
[self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
if (ivar.isSrcClassFromFoundation) return;
ivar.value = [decoder decodeObjectForKey:ivar.name];
它其实就帮我们实现了把所有属性都归档和反归档的操作,那么问题来了,加入我不想所有的文件都归档,我只想归档name和age属性,不想归档gay属性,那怎么办呢?其实MJExtension已经帮我们想好了,只需要调用一下:
[Person setupIgnoredCodingPropertyNames:^NSArray *{
return @[@"gay"];
这个方法就可以了!!!!!!!!
最后附上MJExtension的
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:167994次
积分:2156
积分:2156
排名:第11951名
原创:43篇
转载:12篇
评论:137条
(1)(2)(1)(1)(1)(1)(4)(3)(6)(6)(4)(3)(2)(8)(8)(1)(1)(1)(1)(1)iOS学习笔记38-MJExtension使用 - 简书
下载简书移动应用
写了107510字,被1339人关注,获得了1091个喜欢
iOS学习笔记38-MJExtension使用
一、MJExtension第三方框架
我们在iOS开发过程中,我们常常需要将字典数据(也就是JSON数据)与Model模型之间的转化,例如网络请求返回的微博数据、等等,如果我们自己全部手动去创建模型并赋值,都是一些毫无技术含量的代码,费时费力,而且还可能会赋值出错,让我们很头疼。
MJExtension框架就是为了解决这个问题而设计得第三方开源库。这个开源库是之前传智博客的讲师李明杰老师写的,现在他自己出来做了,我iOS入门都是看李明杰老师的培训视频学习的,他讲得非常好,我非常喜欢他,他也算是我的老师了,他的作品我还是要学习下的。
提供了以下的一些方法实现:
简单的字典 --& 模型
JSON字符串 --& 模型
复杂的字典 --& 模型 (模型里面包含了模型)
复杂的字典 --& 模型 (模型的数组属性里面又装着模型)
复杂的字典 --& 模型(模型属性名和字典的key不一样)
模型 --& 字典
模型数组 --& 字典数组
字典 --& CoreData模型
归档与解档NSCoding
过滤字典的值
MJExtension框架是利用Obj-C的运行时机制编写的,现在iOS开发语言往Swift语言发展,我不太清楚Swift语言是否也有这种特性,该框架以后会不会在Swift语言上也发展下去不得而知,不过这个框架很轻量级,非常适合初级开发者去看它的源码,对理解Obj-C的运行时机制有非常大的帮助。
二、Runtime运行时机制简单了解
Runtime简称运行时,就是系统在运行的时候的一些机制,其中最主要的是消息机制。
OC的函数调用类似于消息发送,属于动态调用过程。在编译的时候并不能决定真正调用哪个函数。事实证明,在编译阶段,OC可以调用任何函数,即使这个函数并未实现,只要申明过就不会报错。而C语言在编译阶段就会报错。只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。
例如,下面的这个代码在编译时会被转化:
/* OC方法调用 */
[obj makeTest];
/* 编译时Runtime会将上面的代码转为下面的消息发送 */
objc_msgSend(obj, @selector(makeText));
iOS的顶层基类NSObject含有一个指向objc_class结构体的isa指针:
@interface NSObject{
typedef struct objc_class *C
struct objc_class {
C // 指向metaclass,也就是静态的Class
Class super_ // 指向其父类
const char * // 类名
// 类的版本信息,初始化默认为0
/* 一些标识信息,如CLS_CLASS(0x1L)表示该类为普通
CLS_META(0x2L)表示该类为metaclass */
long instance_ // 该类的实例变量大小(包括从父类继承下来的实例变量);
struct objc_ivar_list * // 用于存储每个成员变量的地址
/* 与info的一些标志位有关,如是普通class则存储对象方法,如是metaclass则存储类方法; */
struct objc_method_list **methodL
struct objc_cache * // 指向最近使用的方法的指针,用于提升效率;
struct objc_protocol_list * // 存储该类遵守的协议
在objc_msgSend函数的调用过程:
首先通过obj的isa指针找到obj对应的Class。
在Class中先去cache中通过SEL查找对应函数method
若cache中未找到,再去methodLists中查找
若methodLists中未找到,则进入superClass按前面的步骤进行递归查找
若找到method,则将method加入到cache中,以方便下次查找,并通过method中的函数指针跳转到对应的函数中去执行。
如果一直查找到NSObject还没查找到,则会进入消息动态处理流程。
消息动态处理流程:
/* 1. 时机处理之一,在这个方法中我们可以利用runtime的特性动态添加方法来处理 */
+ (BOOL)resolveInstanceMethod:(SEL)
/* 2. 时机处理之二,在这个方法中看代理能不能处理,如果代理对象能处理,则转接给代理对象 */
- (id)forwardingTargetForSelector:(SEL)aS
/* 3. 消息转发之一,该方法返回方法签名,如果返回nil,则转发流程终止,抛出异常 */
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aS
/* 4. 消息转发之二,在该方法中我们可以对调用方法进行重定向 */
- (void)forwardInvocation:(NSInvocation *)anI
所以使用Runtime机制我们就可以动态向类添加方法或属性:
/* 动态向一个类添加属性 */
class_addIvar(kclass, "expression", size, alignment, "*");
/* 动态向一个类添加方法 */
class_addMethod(kclass, @selector(setExpressionFormula:), (IMP)setExpressionFormula, "v@:@");
class_addMethod(kclass, @selector(getExpressionFormula), (IMP)getExpressionFormula, "@@:");
static void setExpressionFormula(id self, SEL cmd, id value){
NSLog(@"call setExpressionFormula");
static id getExpressionFormula(id self, SEL cmd)
NSLog(@"call getExpressionFormula");
v表示void,@表示id类型,:表示SEL类型
"v@:@":表示返回值为void,接受一个id类型、一个SEL类型、一个id类型的方法
"@@:":表示返回值为id类型,接受一个id类型和一个SEL类型参数的方法
具体Runtime运行时使用细节,这里就不细讲,只是简单了解下Runtime是可以做到动态向类添加属性和方法就行。
三、MJExtension使用
MJExtension的大部分方法实现都集成到了分类上,不需要使用新的类,只需要包含头文件MJExtension.h即可。MJExtension在github上的使用说明已经写得十分明白了。
1. 简单的字典 --& 模型
模型类User定义:
typedef enum {
@interface User : NSObject
@property (copy, nonatomic) NSString */* 姓名 */
@property (copy, nonatomic) NSString */* 头像 */
@property (assign, nonatomic)/* 年龄 */
@property (copy, nonatomic) NSString */* 身高 */
@property (strong, nonatomic) NSNumber */* 资产 */
@property (assign, nonatomic) S/* 性别 */
@property (assign, nonatomic, getter=isGay) BOOL/* 是否是同性恋 */
使用实例:
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @20,
@"height" : @"1.55",
@"money" : @100.9,
@"sex" : @(SexFemale),/* 枚举需要使用NSNumber包装 */
@"gay" : @"NO"
//字典转模型,使用的是mj_objectWithKeyValues:方法
User *user = [User mj_objectWithKeyValues:dict];
2. JSON字符串 --& 模型
使用实例:
// 定义一个JSON字符串
NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}";
// JSON字符串转模型
User *user = [User mj_objectWithKeyValues:jsonString];
3. 复杂的字典 --& 模型 (模型里面包含了模型)
模型类Status定义:
@interface Status : NSObject
@property (copy, nonatomic) NSString *
@property (strong, nonatomic) User */* 其他模型类型 */
@property (strong, nonatomic) Status *retweetedS/* 自我模型类型 */
使用实例:
NSDictionary *dict = @{
@"text" : @"Agree!Nice weather!",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
@"retweetedStatus" : @{
@"text" : @"Nice weather!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
//字典转模型,模型里面含有模型
Status *status = [Status mj_objectWithKeyValues:dict];
NSString *text = status.
NSString *name = status.user.
NSString *icon = status.user.
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=Agree!Nice weather!, name=Jack, icon=lufy.png
NSString *text2 = status.retweetedStatus.
NSString *name2 = status.retweetedStatus.user.
NSString *icon2 = status.retweetedStatus.user.
NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
// text2=Nice weather!, name2=Rose, icon2=nami.png
4. 复杂的字典 --& 模型 (模型的数组属性里面又装着模型)
模型类Ad和StatusResult定义:
@interface Ad : NSObject
@property (copy, nonatomic) NSString *
@property (copy, nonatomic) NSString *
@interface StatusResult : NSObject
/** 数组中存储模型Status类型数据 */
@property (strong, nonatomic) NSMutableArray *
/** 数组中存储模型Ad类型数据 */
@property (strong, nonatomic) NSArray *
@property (strong, nonatomic) NSNumber *totalN
#import "MJExtension.h"
/* 数组中存储模型数据,需要说明数组中存储的模型数据类型 */
@implementation StatusResult
/* 实现该方法,说明数组中存储的模型数据类型 */
+ (NSDictionary *)mj_ objectClassInArray{
return @{ @"statuses" : @"Status",
@"ads" : @"Ad"
使用实例:
NSDictionary *dict = @{
@"statuses" : @[
@"text" : @"Nice weather!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
@"text" : @"Go camping tomorrow!",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
@"ads" : @[
@"image" : @"ad01.png",
@"url" : @""
@"image" : @"ad02.png",
@"url" : @""
@"totalNumber" : @"2014"
//字典转模型,支持模型的数组属性里面又装着模型
StatusResult *result = [StatusResult mj_objectWithKeyValues:dict];
//打印博主信息
for (Status *status in result.statuses) {
NSString *text = status.
NSString *name = status.user.
NSString *icon = status.user.
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=Nice weather!, name=Rose, icon=nami.png
// text=Go camping tomorrow!, name=Jack, icon=lufy.png
//打印广告
for (Ad *ad in result.ads) {
NSLog(@"image=%@, url=%@", ad.image, ad.url);
// image=ad01.png, url=
// image=ad02.png, url=
5. 复杂的字典 --& 模型(模型属性名和字典的key不一样)
模型类Bag和Student定义:
@interface Bag : NSObject
@property (copy, nonatomic) NSString *
@property (assign, nonatomic)
@interface Student : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *
@property (copy, nonatomic) NSString *nowN
@property (copy, nonatomic) NSString *oldN
@property (copy, nonatomic) NSString *nameChangedT
@property (strong, nonatomic) Bag *
#import "MJExtension.h"
@implementation
/* 设置模型属性名和字典key之间的映射关系 */
+ (NSDictionary *)mj_replacedKeyFromPropertyName{
/* 返回的字典,key为模型属性名,value为转化的字典的多级key */
@"ID" : @"id",
@"desc" : @"desciption",
@"oldName" : @"name.oldName",
@"nowName" : @"name.newName",
@"nameChangedTime" : @"[1].nameChangedTime",
@"bag" : @"other.bag"
使用实例:
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"kids",
@"name" : @{
@"newName" : @"lufy",
@"oldName" : @"kitty",
@"info" : @[
@"test-data",
@"nameChangedTime" : @"2013-08"
@"other" : @{
@"bag" : @{
@"name" : @"a red bag",
@"price" : @100.7
//字典转模型,支持多级映射
Student *stu = [Student mj_objectWithKeyValues:dict];
NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@",
stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);
// ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
// bagName=a red bag, bagPrice=100.700000
6. 字典数组 --& 模型数组
使用实例:
NSArray *dictArray = @[
@"name" : @"Jack",
@"icon" : @"lufy.png"
@"name" : @"Rose",
@"icon" : @"nami.png"
//字典数组转模型数组,使用的是mj_objectArrayWithKeyValuesArray:方法
NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];
for (User *user in userArray) {
NSLog(@"name=%@, icon=%@", user.name, user.icon);
// name=Jack, icon=lufy.png
// name=Rose, icon=nami.png
7. 模型 --& 字典
使用实例:
//创建一个模型对象
User *user = [[User alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";
Status *status = [[Status alloc] init];
status.user =
status.text = @"Nice mood!";
//模型转字典,使用的是mj_keyValues属性
NSDictionary *statusDict = status.mj_keyV
NSLog(@"%@", statusDict);
text = "Nice mood!";
icon = "lufy.png";
8. 模型数组 --& 字典数组
使用实例:
//创建模型数组
User *user1 = [[User alloc] init];
user1.name = @"Jack";
user1.icon = @"lufy.png";
User *user2 = [[User alloc] init];
user2.name = @"Rose";
user2.icon = @"nami.png";
NSArray *userArray = @[user1, user2];
//模型数组转字典数组,使用的是mj_keyValuesArrayWithObjectArray:方法
NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
NSLog(@"%@", dictArray);
icon = "lufy.png";
icon = "nami.png";
9. 字典 --& CoreData模型
使用实例:
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @20,
@"height" : @1.55,
@"money" : @"100.9",
@"sex" : @(SexFemale),
@"gay" : @"true"
//字典转为CoreData模型
NSManagedObjectContext *context =
User *user = [User mj_objectWithKeyValues:dict
context:context];
[context save:nil];
10. 归档与解档NSCoding
模型类Bag添加实现:
@interface Bag : NSObject &NSCoding&
@property (copy, nonatomic) NSString *
@property (assign, nonatomic)
#import "MJExtension.h"
@implementation Bag
//添加了下面的宏定义
MJExtensionCodingImplementation
/* 实现下面的方法,说明哪些属性不需要归档和解档 */
+ (NSArray *)mj_ignoredCodingPropertyNames{
return @[@"name"];
使用实例:
//创建模型
Bag *bag = [[Bag alloc] init];
bag.name = @"Red bag";
bag.price = 200.8;
//获取归档路径
NSString *file = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/bag.data"];
[NSKeyedArchiver archiveRootObject:bag toFile:file];
Bag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
NSLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
// name=(null), price=200.800000
11. 过滤字典的值
模型类Book实现:
@interface Book: NSObject
@property (copy, nonatomic) NSString *
@property (strong, nonatomic) NSDate *publishedT
#import "MJExtension.h"
@implementation Book
/* 转化过程中对字典的值进行过滤和进一步转化 */
- (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 oldV
使用实例:
NSDictionary *dict = @{
@"name" : @"5分钟突破iOS开发",
@"publishedTime" : @""
//字典转模型,过滤name为nil的情况,把NSString转为NSDate
Book *book = [Book mj_objectWithKeyValues:dict];
NSLog(@"name=%@, publishedTime=%@", book.name, book.publishedTime);
MJExtension的github地址点这里:
如果有什么问题可以在下方评论区中提出!O(∩_∩)O哈!
打赏随意,喜欢我的文章就关注我吧
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮
被以下专题收入,发现更多相似内容:
玩转简书的第一步,从这个专题开始。
想上首页热门榜么?好内容想被更多人看到么?来投稿吧!如果被拒也不要灰心哦~入选文章会进一个队...
· 104000人关注
简书程序员大本营
投稿须知:
1.本专题仅收录与程序有关的文章。
2.请在代码框里写代码,尽量保证可看性。
关注简书官...
· 94413人关注
分享 iOS 开发的知识,解决大家遇到的问题,讨论iOS开发的前沿,欢迎大家投稿~
· 19886人关注
打赏随意,喜欢我的文章就关注我吧
选择支付方式:

我要回帖

更多关于 mjextension 使用 的文章

 

随机推荐