如果项目是纯OC的建议使用,MJExtension是一套字典和模型之间互相转换的超轻量级框架,可以轻松完成:

 字典(JSON) --> 模型(Model)
模型(Model) --> 字典(JSON)
字典数组(JSON Array) --> 模型数组(Model Array)
模型数组(Model Array) --> 字典数组(JSON Array)
如果是swift的项目推荐使用SwiftyJSON,HandyJSON。当然还有其他的解析方式在这里就不说了。如果项目混编我还是喜欢MJExtension。下面说方法:

1.最简单的字典转模型

typedef enum {
SexMale,
SexFemale} Sex;
@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *icon;
@property (assign, nonatomic) int age;
@property (assign, nonatomic) double height;
@property (strong, nonatomic) NSNumber *money;
@property (assign, nonatomic) Sex sex;
@end 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 *text;
/** 微博作者 */
@property (strong, nonatomic) User *user;
/** 转发的微博 */
@property (strong, nonatomic) Status *retweetedStatus;
@end 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.text;
NSString *name = status.user.name;
NSString *icon = status.user.icon;
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=是啊,今天天气确实不错!, name=Jack, icon=lufy.png NSString *text2 = status.retweetedStatus.text;
NSString *name2 = status.retweetedStatus.user.name;
NSString *icon2 = status.retweetedStatus.user.icon;
NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
// text2=今天天气真不错!, name2=Rose, icon2=nami.png

核心代码2

[Status objectWithKeyValues:dict]

3.模型中有个数组属性,数组里面又要装着其它模型

@interface Ad : NSObject
@property (copy, nonatomic) NSString *image;
@property (copy, nonatomic) NSString *url;
@end @interface StatusResult : NSObject
/** 存放着一堆的微博数据(里面都是Status模型) */
@property (strong, nonatomic) NSMutableArray *statuses;
/** 存放着一堆的广告数据(里面都是Ad模型) */
@property (strong, nonatomic) NSArray *ads;
@property (strong, nonatomic) NSNumber *totalNumber;
@end @implementation StatusResult
// 实现这个方法的目的:告诉MJExtension框架statuses和ads数组里面装的是什么模型
/* + (NSDictionary *)objectClassInArray{
return @{
@"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]; }
return nil;}
*/ // 这个方法对比上面的2个方法更加没有侵入性和污染,因为不需要导入Status和Ad的头文件
+ (NSDictionary *)objectClassInArray{
return @{
@"statuses" : @"Status",
@"ads" : @"Ad"
};
}
@end NSDictionary *dict = @{
@"statuses" : @[
@{
@"text" : @"今天天气真不错!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
}
}, @{
@"text" : @"明天去旅游了",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
}
} ],
@"ads" :@[
@{
@"image" : @"ad01.png",
@"url" : @"http://www.ad01.com"
}, @{
@"image" : @"ad02.png",
@"url" : @"http://www.ad02.com"
}
],
@"totalNumber" : @"2014"
}; // 将字典转为StatusResult模型
StatusResult *result = [StatusResult objectWithKeyValues:dict];
NSLog(@"totalNumber=%@", result.totalNumber);
// totalNumber=2014 // 打印statuses数组中的模型属性
for (Status *status in result.statuses) {
NSString *text = status.text;
NSString *name = status.user.name; NSString *icon = status.user.icon;
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=http://www.ad01.com
// image=ad02.png, url=http://www.ad02.com

核心代码3:

在模型内部实现+ (NSDictionary *)objectClassInArray方法

[StatusResult objectWithKeyValues:dict]

4.模型中的属性名和字典中的key不相同(或者需要多级映射)

@interface Bag : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;@end@interface Student : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *desc;
@property (copy, nonatomic) NSString *nowName;
@property (copy, nonatomic) NSString *oldName;
@property (copy, nonatomic) NSString *nameChangedTime;
@property (strong, nonatomic) Bag *bag;
@end @implementation Student
// 实现这个方法的目的:告诉MJExtension框架模型中的属性名对应着字典的哪个key
+ (NSDictionary *)replacedKeyFromPropertyName{
return @{
@"ID" : @"id",
@"desc" : @"desciption",
@"oldName" : @"name.oldName",
@"nowName" : @"name.newName",
@"nameChangedTime" : @"name.info.nameChangedTime",
@"bag" : @"other.bag"
};
} @end 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 = user;
status.text = @"今天的心情不错!"; // 将模型转为字典
NSDictionary *statusDict = status.keyValues;
NSLog(@"%@", statusDict);
/*{ text = "今天的心情不错!";
user = {
icon = "lufy.png";
name = Jack;
};
}*/ // 多级映射的模型
Student *stu = [[Student alloc] init];
stu.ID = @"123";
stu.oldName = @"rose";
stu.nowName = @"jack";
stu.desc = @"handsome";
stu.nameChangedTime = @"2018-09-08"; Bag *bag = [[Bag alloc] init];
bag.name = @"小书包";
bag.price = 205;
stu.bag = bag;
NSDictionary *stuDict = stu.keyValues;NSLog(@"%@", stuDict);
/*
{ desciption = handsome;
id = 123;
name = {
info ={
nameChangedTime = "2018-09-08";
};
newName = jack;
oldName = rose;
};
other = {
bag ={
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"; name = Jack; },
{ icon = "nami.png"; name = Rose; } )*/

核心代码7:

[User keyValuesArrayWithObjectArray:userArray];
 

iOS字典转模型MJExtension使用的更多相关文章

  1. iOS 字典转模型Model

    基本原理 利用 runtime 原理,获取模型中所有实例变量列表,根据实例变量以此获取模型中成员变量的名称和属性类型,区分Foundation和自定义属性,需要对NSDictionary和NSArra ...

  2. ios 字典转模型

    <pre name="code" class="objc">#import <Foundation/Foundation.h> @int ...

  3. iOS开发——网络篇——JSON和XML,NSJSONSerialization ,NSXMLParser(XML解析器),NSXMLParserDelegate,MJExtension (字典转模型),GDataXML(三方框架解析XML)

    一.JSON 1.JSON简介什么是JSONJSON是一种轻量级的数据格式,一般用于数据交互服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外) JSON的格式很像OC中的字典 ...

  4. IOS 字典模型互转框架 MJExtension

    IOS 字典模型互转框架 MJExtension   能做什么? MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能 字典(JSON) -->  ...

  5. iOS开发——笔记篇&关于字典plist读取/字典转模型/自定义View/MVC/Xib的使用/MJExtension使用总结

    关于字典plist读取/字典转模型/自定义View/MVC/Xib的使用/MJExtension使用总结 一:Plist读取 /************************************ ...

  6. ios开发网络学习二:URL转码以及字典转模型框架MJExtension的使用

    一:url转码,当url中涉及到中文的时候,要考虑转码,用UTF8对中文的url进行转码 #import "ViewController.h" @interface ViewCon ...

  7. IOS第四天-新浪微博 -存储优化OAuth授权账号信息,下拉刷新,字典转模型

    *************application - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOpti ...

  8. 字典转模型框架 Mantle的使用:国外程序员最常用的iOS模型

    Mantle简介 Mantle 是iOS和Mac平台下基于Objective-C编写的一个简单高效的模型层框架. Mantle能做什么 Mantle可以轻松把JSON数据.字典(Dictionary) ...

  9. iOS开发——高级技术精选OC篇&Runtime之字典转模型实战

    Runtime之字典转模型实战 如果您还不知道什么是runtime,那么请先看看这几篇文章: http://www.cnblogs.com/iCocos/p/4734687.html http://w ...

随机推荐

  1. 【原创】源码角度分析Android的消息机制系列(三)——ThreadLocal的工作原理

    ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 先看Android源码(API24)中对ThreadLocal的定义: public class ThreadLocal<T> 即 ...

  2. thinkphp5.0学习笔记(三)获取信息,变量,绑定参数

    1.构造函数: 控制器类必须继承了\think\Controller类,才能使用: 方法_initialize 代码: <?php namespace app\lian\controller; ...

  3. MongoDB--数据库与Collection注意事项

    <h2>    <strong>注意事项:</strong></h2>1.数据库名注意应该全部小写,不能包含空格,最大长度为64K名称<br /& ...

  4. openfire极限优化

    日志优化   默认是 用info 级别,最好不用openfire原生的打日志方式.   离线消息用存储不打回方式,不要用打回方式   xmpp.offline.type=store_and_drop ...

  5. Java注解--实现简单读取excel

    实现工具类 利用注解实现简单的excel数据读取,利用注解对类的属性和excel中的表头映射,使用Apache的poi就不用在业务代码中涉及row,rows这些属性了. 定义注解: @Retentio ...

  6. MySQL如何有效的存储IP地址及字符串IP和数值之间如何转换

    mysql> select inet_aton('192.168.0.1'); +--------------------------+ | inet_aton('192.168.0.1') | ...

  7. [leetcode-312-Burst Balloons]

    Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by ...

  8. 【Android Developers Training】 28. 将用户带领到另一个应用

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  9. Vim正则通配符使用心得

    目的 实现替换 c f[i][j][k] -> f[k][i][j] f[i + 1][j][k] -> f[k][i + 1][j] f[i + 1][j + NY][k] -> ...

  10. accp8.0转换教材第9章JQuery相关知识理解与练习

    自定义动画 一.单词部分: ①animate动画②remove移除③validity有效性 ④required匹配⑤pattern模式 二.预习部分 1.简述JavaScript事件和jquery事件 ...