MJExtension的使用

1.簡(jiǎn)單的字典 --> 模型
----核心代碼 mj_objectWithKeyValues:
2.JSON字符串 --> 模型
----核心代碼 mj_objectWithKeyValues:
3.復(fù)雜的字典 --> 模型 (模型里面包含了模型)
----核心代碼 mj_objectWithKeyValues:
4.模型中有個(gè)數(shù)組屬性,數(shù)組里面又要裝著其它模型
----核心代碼 mj_objectWithKeyValues:和mj_objectClassInArray
5.模型中的屬性名和字典中的key不相同(或者需要多級(jí)映射)
----核心代碼 mj_objectWithKeyValues:和mj_replacedKeyFromPropertyName
6.將一個(gè)字典數(shù)組轉(zhuǎn)成模型數(shù)組
----核心代碼 mj_objectArrayWithKeyValuesArray
7.將一個(gè)模型轉(zhuǎn)成字典
----核心代碼 mj_keyValues
8.將一個(gè)模型數(shù)組轉(zhuǎn)成字典數(shù)組
----核心代碼 mj_keyValuesArrayWithObjectArray


1.簡(jiǎn)單的字典 --> 模型
核心代碼 mj_objectWithKeyValues:

typedef enum {
        SexMale,
        SexFemale
    } Sex;
    @interface User : NSObject
    @property (copy, nonatomic) NSString *name;/* 姓名 */
    @property (copy, nonatomic) NSString *icon;/* 頭像 */
    @property (assign, nonatomic) unsigned int age;/* 年齡 */
    @property (copy, nonatomic) NSString *height;/* 身高 */
    @property (strong, nonatomic) NSNumber *money;/* 資產(chǎn) */
    @property (assign, nonatomic) Sex sex;/* 性別 */
    @property (assign, nonatomic, getter=isGay) BOOL gay;/* 是否是同性戀 */
    @end
    //簡(jiǎn)單的字典
    NSDictionary *dict_user = @{
                                @"name" : @"Jack",
                                @"icon" : @"lufy.png",
                                @"age" : @20,
                                @"height" : @"1.55",
                                @"money" : @100.9,
                                @"sex" : @(SexFemale),/* 枚舉需要使用NSNumber包裝 */
                                @"gay" : @YES
                                };
    User *user = [User mj_objectWithKeyValues:dict_user];
    NSLog(@"MJ---%@----%@---%u---%@---%@---%u----%d",user.name,user.icon,user.age,user.height,user.money,user.sex,user.gay);
    //打印結(jié)果
    //2016-07-04 11:06:59.746 PPDemos[2432:73824] MJ---Jack----lufy.png---20---1.55---100.9---1----1

2.JSON字符串 --> 模型
核心代碼 mj_objectWithKeyValues:

// 定義一個(gè)JSON字符串 
NSString *jsonStr = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}"; 
User *user = [User mj_objectWithKeyValues:jsonStr]; 
NSLog(@"MJ---%@----%@---%u",user.name,user.icon,user.age); 
//打印結(jié)果 
//2016-07-04 11:16:04.655 PPDemos[2563:78561] MJ---Jack----lufy.png---20

3.復(fù)雜的字典 --> 模型 (模型里面包含了模型)
核心代碼 mj_objectWithKeyValues:

//復(fù)雜的字典[模型中有個(gè)數(shù)組屬性,數(shù)組里面又要裝著其他模型的字典]
    NSDictionary *dict_m8m = @{
                               @"text" : @"Agree!Nice weather!",
                               @"user" : @{
                                       @"name" : @"Jack",
                                       @"icon" : @"lufy.png"
                                       },
                               @"retweetedStatus" : @{
                                       @"text" : @"Nice weather!",
                                       @"user" : @{
                                               @"name" : @"Rose",
                                               @"icon" : @"nami.png"
                                               }
                                       }
                               };
    #import <Foundation/Foundation.h>
    @class User;
    @class Status;
    //Status模型
    @interface Status : NSObject
    @property (copy, nonatomic) NSString *text;
    @property (strong, nonatomic) User *user;/* 其他模型類型 */
    @property (strong, nonatomic) Status *retweetedStatus;/* 自我模型類型 */
    @end
    //
    //字典轉(zhuǎn)模型,模型里面含有模型
    Status *status = [Status mj_objectWithKeyValues:dict_m8m];
    NSString *text = status.text;
    NSString *name = status.user.name;
    NSString *icon = status.user.icon;
    NSLog(@"mj-----text=%@, name=%@, icon=%@", text, name, icon);
    NSString *text2 = status.retweetedStatus.text;
    NSString *name2 = status.retweetedStatus.user.name;
    NSString *icon2 = status.retweetedStatus.user.icon;
    NSLog(@"mj-----text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
    // //打印結(jié)果
    //2016-07-04 11:45:39.675 PPDemos[2781:87089] mj-----text=Agree!Nice weather!, name=Jack, icon=lufy.png
    //2016-07-04 11:45:39.675 PPDemos[2781:87089] mj-----text2=Nice weather!, name2=Rose, icon2=nami.png

4.模型中有個(gè)數(shù)組屬性,數(shù)組里面又要裝著其它模型
核心代碼 mj_objectWithKeyValues:和mj_objectClassInArray

    @interface Ad : NSObject
    @property (copy, nonatomic) NSString *image;
    @property (copy, nonatomic) NSString *url;
    @end
    @interface StatusResult : NSObject
    /** 存放著一堆的微博數(shù)據(jù)(里面都是Status模型) */
    @property (strong, nonatomic) NSMutableArray *statuses;
    /** 存放著一堆的廣告數(shù)據(jù)(里面都是Ad模型) */
    @property (strong, nonatomic) NSArray *ads;
    @property (strong, nonatomic) NSNumber *totalNumber;
    @end
    #import "StatusResult.h"
    #import "MJExtension.h"
    @implementation StatusResult
    /* 數(shù)組中存儲(chǔ)模型數(shù)據(jù),需要說明數(shù)組中存儲(chǔ)的模型數(shù)據(jù)類型 */
    +(NSDictionary *)mj_objectClassInArray {
        return @{
                 @"statuses" : @"Status",
                 @"ads" : @"Ad"
                 };
    } @end

在VC里實(shí)現(xiàn)以下來解析數(shù)據(jù)

//模型中有個(gè)數(shù)組屬性,數(shù)組里面又要裝著其他模型
    NSDictionry *dict_m8a = @{
                  @"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" : @"http://www.ad01.com"
                              },
                          @{
                              @"image" : @"ad02.png",
                              @"url" : @"http://www.ad02.com"
                              }
                          ],
                  @"totalNumber" : @"2014"
                  };
    【重點(diǎn),核心】》》數(shù)組中存儲(chǔ)模型數(shù)據(jù),需要說明數(shù)組中存儲(chǔ)的模型數(shù)據(jù)類型 《《
    /*
     [StatusResult mj_setupObjectClassInArray:^NSDictionary *{
             return @{
                 @"statuses" : @"Status",
                 // @"statuses" : [Status class],
                 @"ads" : @"Ad"
                 // @"ads" : [Ad class]
             };
     }];
    */
     // Equals: StatusResult.m implements +mj_objectClassInArray method.
    
    //以上方法在VC里寫,如果多個(gè)地方解析該model,就要寫多次,最好在model的.m文件寫!
    //字典轉(zhuǎn)模型,支持模型的數(shù)組屬性里面又裝著模型
    StatusResult *result = [StatusResult mj_objectWithKeyValues:dict_m8a];
    //打印博主信息
    for (Status *status in result.statuses) {
        NSString *text = status.text;
        NSString *name = status.user.name;
        NSString *icon = status.user.icon;
        NSLog(@"mj---text=%@, name=%@, icon=%@", text, name, icon);
        
    }
    //打印廣告
    for (Ad *ad in result.ads) {
        NSLog(@"mj---image=%@, url=%@", ad.image, ad.url);
        
    }
    //打印結(jié)果
    //2016-07-04 13:47:58.994 PPDemos[3353:113055] mj---text=Nice weather!, name=Rose, icon=nami.png
    //2016-07-04 13:47:58.995 PPDemos[3353:113055] mj---text=Go camping tomorrow!, name=Jack, icon=lufy.png
    //2016-07-04 13:47:58.995 PPDemos[3353:113055] mj---image=ad01.png, url=http://www.ad01.com
    //2016-07-04 13:47:58.995 PPDemos[3353:113055] mj---image=ad02.png, url=http://www.ad02.com

5.模型中的屬性名和字典中的key不相同(或者需要多級(jí)映射)
核心代碼 mj_objectWithKeyValues:和mj_replacedKeyFromPropertyName
//多級(jí)映射,用點(diǎn)語法設(shè)置

    @interface Bag : NSObject
    @property (copy, nonatomic) NSString *name;
    @property (assign, nonatomic) double price;
    @end
    #import <Foundation/Foundation.h>
    @class Bag;
    @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
    +(NSDictionary *)mj_replacedKeyFromPropertyName {
        // 實(shí)現(xiàn)這個(gè)方法的目的:告訴MJExtension框架模型中的屬性名對(duì)應(yīng)著字典的哪個(gè)key
        return @{
                 @"ID" : @"id",
                 @"desc" : @"desciption",
                 @"oldName" : @"name.oldName",
                 @"nowName" : @"name.newName",
                 @"nameChangedTime" : @"name.info[1].nameChangedTime",
                 @"bag" : @"other.bag"
                 };
    } @end
    NSDictionry *dict_nokey = @{
                                @"id" : @"20",
                                @"desciption" : @"kids",
                                @"name" : @{
                                        @"newName" : @"lufy",
                                        @"oldName" : @"kitty",
                                        @"info" : @[
                                                @"test-data", @{
                                                    @"nameChangedTime" : @"2013-08"
                                                    
                                                    }
                                                ]
                                        },
                                @"other" : @{
                                        @"bag" : @{
                                                @"name" : @"a red bag",
                                                @"price" : @100.7
                                                }
                                        }
                                };
    //// How to map
    // [Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            // return @{
            // @"ID" : @"id",
            // @"desc" : @"desciption",
            // @"oldName" : @"name.oldName",
            // @"nowName" : @"name.newName",
            // @"nameChangedTime" : @"name.info[1].nameChangedTime",
            // @"bag" : @"other.bag"
            //};
    //}];
// // Equals: Student.m implements +mj_replacedKeyFromPropertyName method.
//字典轉(zhuǎn)模型,支持多級(jí)映射
Student *stu = [Student mj_objectWithKeyValues:dict_nokey];
//打印
NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@", stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime); NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
//2016-07-04 14:20:28.082 PPDemos[3602:126004] ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
//2016-07-04 14:20:28.082 PPDemos[3602:126004] bagName=a red bag, bagPrice=100.700000

6.將一個(gè)字典數(shù)組轉(zhuǎn)成模型數(shù)組
核心代碼 mj_objectArrayWithKeyValuesArray

NSArray *dictArray = @[
                              @{
                                  @"name" : @"Jack",
                                  @"icon" : @"lufy.png"
                               },
                              @{
                                  @"name" : @"Rose",
                                  @"icon" : @"nami.png"
                               }
                          ];
    //字典數(shù)組轉(zhuǎn)模型數(shù)組,使用的是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.將一個(gè)模型轉(zhuǎn)成字典
核心代碼 mj_keyValues

User *user = [[User alloc] init];
    user.name = @"Jack";
    user.icon = @"lufy.png";
    //
    Status *status = [[Status alloc] init];
    status.user = user;
    status.text = @"Nice mood!";
    //
    //模型轉(zhuǎn)字典,使用的是mj_keyValues屬性
    NSDictionary *statusDict = status.mj_keyValues;
    NSLog(@"%@", statusDict);
    /*
     {
     text = "Nice mood!";
     user = { icon = "lufy.png"; name = Jack;
     };
     }
     */

8.將一個(gè)模型數(shù)組轉(zhuǎn)成字典數(shù)組
核心代碼 mj_keyValuesArrayWithObjectArray

//創(chuàng)建模型數(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ù)組,使用的是mj_keyValuesArrayWithObjectArray:方法
    NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
    NSLog(@"%@", dictArray);
    /*
     (
     {
     icon = "lufy.png";
     name = Jack;
     },
     {
     icon = "nami.png";
     name = Rose;
     }
     )
     */

更多用法

參考NSObject+MJKeyValue.h
參考NSObject+MJCoding.h

轉(zhuǎn)自MJExtension使用指導(dǎo)(最新)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 推薦一下: iOS鏈?zhǔn)絼?chuàng)建UI終結(jié)者 ? PPMaker 2018-05-10 MJ早更新了MJExtensi...
    PPAbner閱讀 40,046評(píng)論 26 66
  • MJExtension的github地址 1. Getting Started【開始使用】 只需要一行代碼,就能實(shí)...
    iYeso閱讀 1,010評(píng)論 0 2
  • 一、MJExtension第三方框架我們?cè)趇OS開發(fā)過程中,我們常常需要將字典數(shù)據(jù)(也就是JSON數(shù)據(jù))與Mode...
    階梯閱讀 5,633評(píng)論 2 3
  • JSON 轉(zhuǎn) Model JSONString 轉(zhuǎn) Model Model 中包含其他 Model Model 中...
    Huangbaoqin閱讀 1,375評(píng)論 0 2
  • 使用MJExtension框架,是最常見的不過了,本文主要關(guān)注以下幾點(diǎn),這地方就不在造輪子了,發(fā)現(xiàn)一個(gè)講的比較好的...
    鄉(xiāng)水情緣閱讀 484評(píng)論 0 0