ModelToDictionary
前言
在项目开发中,将Model对象数据转换成NSDictionary对象(或包含NSDictionary对象的数组),然后通过接口提交给服务器是开发中频繁需要做的事情,然而手动的去拼写NSDictionary对象既麻烦又容易出错。所以我就写了这样的一个功能,可以将Model对象数据转换成NSDictionary对象。并且可以重写Model类方法来重命名生成的字典的key以及可以屏蔽掉一些在生成NSDictionary对象不需要的键值对。
1.只需在项目里引入NSObject+Dictionary类别,然后调用“-(NSDictionary *)toDictionary”方法例如:
//给test对象赋值(注意填写正确的文件路径)
NSString *str=[NSString stringWithContentsOfFile:@"/Users/POSUN/Documents/ModelToDictionary/ModelToDictionary/TestJson.json" encoding:NSUTF8StringEncoding error:nil];
if (str == nil){
return;}
NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error=nil;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
TEST *test=[[TEST alloc] init];
[test setValuesForKeysWithDictionary:dic];
//将test对象转换传NSDictionary对象
NSDictionary *testDic=[test toDictionary];
NSLog("%@",testDic);
复制代码
运行结果:
2018-07-16 17:25:07.007223+0800 ModelToDictionary[3678:582786] {
salesOrder = {
assistant1 = xxx;
assistantId = 000001;
deliveryType = Y;
deliveryTypeName = "\U9001\U8d27\U4e0a\U95e8";
needInstall = Y;
number = 4534;
orderDate = 1525507xxx;
orgId = A;
orgName = "xxx\U6709\U9650\U516c\U53f8";
priceSum = "3.000000";
refundType = 1;
requireArriveDate = 1525593xxx;
salesOrderParts = {
billPrice = "3.00";
goods = {
Id = "";
enableSn = "";
giftFlag = "";
good