YYModel的使用

iOS开发中总会用到各种JSON与模型相互转换的需求,之前的项目中一直使用MJExtension,但是最近发现一个轻量级的库YYModel,使用简单,性能也很不错,接下来就说说YYModel的一些简单的用法及注意事项.

  • JSON转换为模型,或者模型转换为JSON的例子
//JSON
{
    accountId = "<null>";
    avatarUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
    unionId = o2t87wKAR1pNRZR0cnReBT608mok;
    userid = 11703346;
    wxNickName = "\U90a3\U5496";
}
//Model
@interface MyFansModel : NSObject
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@end
//JSON转换为模型
MyFansModel *fansModel = [MyFansModel yy_modelWithJSON:dic];
MyFansModel *fansModel = [MyFansModel yy_modelWithDictionary:dic];

//模型转换为JSON
NSDictionary *json = [fansModel yy_modelToJSONObject];
  • 手动创建的模型和服务端返回的模型属性名称不一致时的例子
//JSON
{ "merchantId" = "<null>";
  "avatar" = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
  "unionID" = "o2t87wKAR1pNRZR0cnReBT608mok";
  "userID" = "11703346";
  "userName" = "贺建奎";
}
//Model
//.h中
#import <YYModel.h>
@interface MyFansModel : NSObject <YYModel>
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@end
//.m中
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper
{
    return @{@"avatarUrl" : @"avatar",
             @"wxNickName" : @"userName",
             @"accountId" : @"merchantId",
             @"unionId" : @"unionID",
             @"userid":@"userID",
             };
}
MyFansModel *fansModel = [MyFansModel yy_modelWithJSON:dic];
MyFansModel *fansModel = [MyFansModel yy_modelWithDictionary:dic];
  • 模型套模型的例子
//JSON
{
    citys =   (
                {
            area = "<null>";
            areaId = "<null>";
            areas =             (
                                {
                    area = "\U4e1c\U57ce\U533a";
                    cityid = 110100;
                    id = 110101;
                    status = 1;
                },
                                {
                    area = "\U897f\U57ce\U533a";
                    cityid = 110100;
                    id = 110102;
                    status = 1;
                },
                                {
                    area = "\U5d07\U6587\U533a";
                    cityid = 110100;
                    id = 110103;
                    status = 1;
                },
                                {
                    area = "\U5ba3\U6b66\U533a";
                    cityid = 110100;
                    id = 110104;
                    status = 1;
                },
                                {
                    area = "\U671d\U9633\U533a";
                    cityid = 110100;
                    id = 110105;
                    status = 1;
                },
                                {
                    area = "\U4e30\U53f0\U533a";
                    cityid = 110100;
                    id = 110106;
                    status = 1;
                },
                                {
                    area = "\U77f3\U666f\U5c71\U533a";
                    cityid = 110100;
                    id = 110107;
                    status = 1;
                },
                                {
                    area = "\U6d77\U6dc0\U533a";
                    cityid = 110100;
                    id = 110108;
                    status = 1;
                },
                                {
                    area = "\U95e8\U5934\U6c9f\U533a";
                    cityid = 110100;
                    id = 110109;
                    status = 1;
                },
                                {
                    area = "\U623f\U5c71\U533a";
                    cityid = 110100;
                    id = 110111;
                    status = 1;
                },
                                {
                    area = "\U901a\U5dde\U533a";
                    cityid = 110100;
                    id = 110112;
                    status = 1;
                },
                                {
                    area = "\U987a\U4e49\U533a";
                    cityid = 110100;
                    id = 110113;
                    status = 1;
                },
                                {
                    area = "\U660c\U5e73\U533a";
                    cityid = 110100;
                    id = 110114;
                    status = 1;
                },
                                {
                    area = "\U5927\U5174\U533a";
                    cityid = 110100;
                    id = 110115;
                    status = 1;
                },
                                {
                    area = "\U6000\U67d4\U533a";
                    cityid = 110100;
                    id = 110116;
                    status = 1;
                },
                                {
                    area = "\U5e73\U8c37\U533a";
                    cityid = 110100;
                    id = 110117;
                    status = 1;
                }
            );
            city = "\U5e02\U8f96\U533a";
            cityId = "<null>";
            id = 110100;
            province = "<null>";
            provinceid = 110000;
            status = 1;
        },
                {
            area = "<null>";
            areaId = "<null>";
            areas =             (
                                {
                    area = "\U5bc6\U4e91\U53bf";
                    cityid = 110200;
                    id = 110228;
                    status = 1;
                },
                                {
                    area = "\U5ef6\U5e86\U53bf";
                    cityid = 110200;
                    id = 110229;
                    status = 1;
                }
            );
            city = "\U53bf";
            cityId = "<null>";
            id = 110200;
            province = "<null>";
            provinceid = 110000;
            status = 1;
        }
    );
    id = 110000;
    province = "\U5317\U4eac\U5e02";
    status = 1;
}
//Model
//.h
//BaseModel 只是为了将id映射为_id 
#import <YYModel.h>
NS_ASSUME_NONNULL_BEGIN

@interface BaseModel : NSObject <YYModel>

/// id 映射为 _id
@property (nonatomic, copy) NSString *_id;

@end
//.m
+(NSDictionary<NSString *,id> *)modelCustomPropertyMapper
{
    return @{@"_id": @"id"};
}
//真正使用的模型的.h文件
@interface AreaModel : BaseModel
@property (nonatomic, copy) NSString *area;
@property (nonatomic, copy) NSString *cityid;
@property (nonatomic, copy) NSString *status;
@end

@interface CityModel : BaseModel
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *provinceid;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, strong) NSArray *areas;
@end

@interface ProvinceModel : BaseModel

@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, strong) NSArray *citys;

@end
//.m 文件
@implementation AreaModel

@end

@implementation CityModel
+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"areas" : [AreaModel class]};
}
@end

@implementation ProvinceModel

+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"citys" : [CityModel class]};
}
@end

//将JSON转换为模型
ProvinceModel *provinceModel = [ProvinceModel yy_modelWithJSON:dic];
CityModel *cityModel = provinceModel.citys[0];
AreaModel *areaModel = cityModel.areas[0];
  • 数组里面存放字典类型转换为模型的例子
//JSON
(
{
"accountId" = "<null>";
"avatarUrl" = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
"unionId" = "o2t87wKAR1pNRZR0cnReBT608mok";
"userid" = "11703346",
"wxNickName" = "贺建奎"
},
{
"accountId" = "<null>";
"avatarUrl" = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
"unionId" = "o2t87wKAR1pNRZR0cnReBT608mok";
"userid" = "11293020";
"wxNickName" = "撒撒";
}
);
//Model
@interface MyFansModel : NSObject
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@end
//转换为模型
NSArray<MyFansModel *> *myFansModelArray = [NSArray yy_modelArrayWithClass:[MyFansModel class] json:array];
  • 容器类属性
//JSON
{
"schoolName" = "张三";
"teachers" =  (
      {"teacherName"= "Sndday","teacherAge" = 50};
      {"teacherName" = "Ssasas","teacherAge" = 70};
      {"teacherName" = "Snddasa","teacherAge"= 30)}
      );
};
//Model
//.h
#import <YYModel.h>


@interface SchoolModel : NSObject <YYModel>

@property (nonatomic, copy) NSString *schoolName;
@property (nonatomic, copy) NSArray *teachers;

@end
//.m
#import "TeacherModel.h"

@implementation SchoolModel

+ (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass
{
    return @{@"teachers":[TeacherModel class]};
}

@end
//TeacherModel

@interface TeacherModel : NSObject

@property (nonatomic, copy) NSString *teacherName;
@property (nonatomic, assign) NSInteger teacherAge;

@end

//转换为模型
NSDictionary *dic = @{
  @"schoolName":@"张三",
  @"teachers":@[
          @{@"teacherName":@"Sndday",@"teacherAge":@(50)},
          @{@"teacherName":@"Ssasas",@"teacherAge":@(70)},
          @{@"teacherName":@"Snddasa",@"teacherAge":@(30)}
          ],
  };

SchoolModel *model = [SchoolModel yy_modelWithJSON:dic];

TeacherModel *teacherModel = model.teachers[0];

  • 黑名单,即加入黑名单的字段会被忽略不会转换
//JSON
{
    accountId = "<null>";
    avatarUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
    unionId = o2t87wKAR1pNRZR0cnReBT608mok;
    userid = 11703346;
    wxNickName = "\U90a3\U5496";
}
//Model
//.h
#import <YYModel.h>
@interface MyFansModel : NSObject <YYModel>
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@end
//.m
+ (NSArray *)modelPropertyBlacklist 
{
    return @[@"avatarUrl", @"accountId"];
}
//将JSON转换为模型,转换出来的模型中的```avatarUrl```和```accountId```的值为```nil```
MyFansModel *fansModel = [MyFansModel yy_modelWithJSON:dic];
  • 白名单 即只处理加入白名单的字段,其余字段忽略掉
//JSON
{
    accountId = "<null>";
    avatarUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
    unionId = o2t87wKAR1pNRZR0cnReBT608mok;
    userid = 11703346;
    wxNickName = "\U90a3\U5496";
}
//Model
//.h
#import <YYModel.h>
@interface MyFansModel : NSObject <YYModel>
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@end
//.m
+ (NSArray *)modelPropertyWhitelist 
{
    return @[@"avatarUrl", @"accountId"];
}
//将JSON转换为模型,转换出来的模型中的```avatarUrl```和```accountId```的值为```nil```
MyFansModel *fansModel = [MyFansModel yy_modelWithJSON:dic];
  • 数据校验与自定义转化
{
    accountId = "<null>";
    avatarUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/sqicFCgiaheqCFbjrYgTmwXUQOB5l5Iyo47cVVp2cLlHARck6XgXscqicJ2ZVibicCbGH4iaVcQz8ptXqbV6n9ic5iaL9g/132";
    unionId = o2t87wKAR1pNRZR0cnReBT608mok;
    userid = 11703346;
    wxNickName = "\U90a3\U5496";
}
#import <YYModel.h>
@interface MyFansModel : NSObject <YYModel>
@property (nonatomic, strong) NSString *avatarUrl;
@property (nonatomic, strong) NSString *wxNickName;
@property (nonatomic, strong) NSString *accountId;
@property (nonatomic, strong) NSString *unionId;
@property (nonatomic, strong) NSString *userid;
@property (nonatomic, strong) NSString *resultStr;
@end
//.m
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    NSString *timestamp = dic[@"accountId"];
    if ([timestamp isEqualToString:@"<null>"]) return NO;
    _resultStr = [NSString stringWithFormat:@"那撒上%@",timestamp];
    return YES;
}
//将JSON转换为模型
    MyFansModel *fansModel = [MyFansModel yy_modelWithJSON:dic];

上述例子由于对accountId做了校验,所以如果accountId不符合要求,该JSON将不会被解析,当然你也可以在这里做一些自动转换不能完成的工作,比如将后端返回的时间戳转换为时间字符串等自定义的操作。

至此,关于YYModel的相关用法已经全部说完了,如果由哪些说的不对的地方,欢迎指正。如果喜欢,欢迎点赞关注!!!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容