Model--MJExtension

參考文檔

MJExtension是一套字典和模型之間互相轉(zhuǎn)換的超輕量級框架
字典(JSON) --> 模型(Model)
模型(Model) --> 字典(JSON)

字典數(shù)組(JSON Array) --> 模型數(shù)組(Model Array)
模型數(shù)組(Model Array) --> 字典數(shù)組(JSON Array)

MJExtension JSONModel、Mantle區(qū)別

  • MJExtension > JSONModel > Mantle(轉(zhuǎn)換效率)

  • JSONModel: 要求所有模型類必須繼承自JSONModel基類
    MJExtension:不需要繼承任何特殊基類,毫無污染,毫無侵入性
    Mantle: 要求所有模型類必須繼承自MTModel基類

  • 個人感覺上MJExtension容錯性更高一些

1.字典轉(zhuǎn)模型
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 (nonatomic, strong) NSString *birthday;
@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 mj_objectWithKeyValues:dict];

改變映射關(guān)系
如果后臺返回的字段跟模型的字段不一致,可以在.m文件中實現(xiàn)匹配方法

+ (NSDictionary *)mj_replacedKeyFromPropertyName{
    return @{
                //前邊的是你想用的key,后邊的是返回的key
                 @"name":@"name_nick"
                };
}

復(fù)雜映射更改

@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框架模型中的屬性名對應(yīng)著字典的哪個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                                                              
                                                 }                       
                                     }                   
};

// 將字典轉(zhuǎn)為Student模型
Student *stu = [Student objectWithKeyValues:dict];

數(shù)據(jù)簡單加工
后臺如果返回時間戳,但我們需要指定時間格式,可以在.m 文件中實現(xiàn)數(shù)據(jù)處理方法

- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property{

     if ([property.name isEqualToString:@"birthday"]) {
         if (oldValue) {
              // 格式化時間
              NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
              formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
              [formatter setDateStyle:NSDateFormatterMediumStyle];
              [formatter setTimeStyle:NSDateFormatterShortStyle];
              [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
              NSDate* date = [NSDate dateWithTimeIntervalSince1970:[oldValue doubleValue]];
              NSString* dateString = [formatter stringFromDate:date];
              return dateString;
            }

        }else {
            return @"日期有誤";
        }
    return oldValue;
}

=======================================
以上轉(zhuǎn)化為Model 的方法都是 mj_objectWithKeyValues
=======================================

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"                    
                                   }                
                       }            
};

// 將字典轉(zhuǎn)為Status模型
Status *status = [Status objectWithKeyValues:dict];

3. 模型中有數(shù)組
如果模型中有包含模型的數(shù)組,則需要實現(xiàn)相應(yīng)方法

@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數(shù)組里面模型
 + (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個方法更加沒有侵入性和污染,因為不需要導(dǎo)入Status和Ad的頭文件
+ (NSDictionary *)objectClassInArray{    
    return @{    
              #前邊,是屬性數(shù)組的名字,后邊就是類名     
              @"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"                    
};

         // 將字典轉(zhuǎn)為StatusResult模型
         StatusResult *result = [StatusResult objectWithKeyValues:dict];

         // 打印statuses數(shù)組中的模型屬性
         for (Status *status in result.statuses) {    
                 NSLog(@"text=%@, name=%@", text, name);
          }
         // 打印ads數(shù)組中的模型屬性
         for (Ad *ad in result.ads) {    
                 NSLog(@"image=%@, url=%@", ad.image, ad.url);
       }

4. 字典數(shù)組轉(zhuǎn)成模型數(shù)組

NSArray *dictArray = @[                       
                        @{                           
                           @"name" : @"Jack",                           
                           @"icon" : @"lufy.png",                        
                         },                       
                        @{                           
                           @"name" : @"Rose",                           
                           @"icon" : @"nami.png",                        
                         }                    
                       ];

// 將字典數(shù)組轉(zhuǎn)為User模型數(shù)組
NSArray *userArray = [User objectArrayWithKeyValuesArray:dictArray];
// 打印userArray數(shù)組中的User模型屬性
for (User *user in userArray) {   
      NSLog(@"name=%@, icon=%@", user.name, user.icon);
}

5.模型轉(zhuǎn)字典

// 新建模型
User *user = [[User alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";

Status *status = [[Status alloc] init];
status.user = user;
status.text = @"今天的心情不錯!";


// 將模型轉(zhuǎn)為字典
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;

6. 模型數(shù)組轉(zhuǎn)字典數(shù)組

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];
// 將模型數(shù)組轉(zhuǎn)為字典數(shù)組
NSArray *dictArray 
= [User keyValuesArrayWithObjectArray:userArray];

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容