YYModel的使用

GitHub原文:https://github.com/ibireme/YYModel
或者直接打开.h文件查看如何使用。
说白了,
就是Json-Model-Dic三者相互转化,并处理了null(转化为nil或者0)。
重点:
这是一个NSObject的Category,无须继承,可以直接使用!


                           **--NSObject的方法--**

1.json、dic转model(用于解析)
+ (nullable instancetype)yy_modelWithJSON:(id)json;
+ (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;

2.model转json(用于提交数据)
- (nullable id)yy_modelToJSONObject;
- (nullable NSString *)yy_modelToJSONString;

3.打印model对象 (用于调试)
- (NSString *)yy_modelDescription;



                    **-- NSArray类方法 --** 
@interface NSArray (YYModel)


//cls:Model类
//json:后台的json数据
+ (nullable NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json;

例子:
NSArray *array = [NSArray yy_modelArrayWithClass:[ConsumeModel class] json:result.response[@"list"]];
其中,参数list是包含多个字典的大数组(json格式)
返回的是包含多个model的数组





我的技巧

1.Model 属性名和 JSON 中的 Key 不相同, 比如后台给你“id”。

// JSON:
{
    "n":"Harry Pottery",
    "p": 256,
    "ext" : {
        "desc" : "A book written by J.K.Rowing."
    },
    "id" : 100010
}

// Model:
@interface Book : NSObject
@property NSString *name;
@property NSInteger page;
@property NSString *desc;
@property NSString *bookID;//自定义的id
@end

@implementation Book

//If the key in JSON/Dictionary does not match to the model's property name, implements this method and returns the additional(额外的) mapper.
+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"name" : @"n",
             @"page" : @"p",
             @"desc" : @"ext.desc",
             @"bookID" : @"id"};
}
@end




2.在后台Json转化为自定义的model后,如果想要对数据进行后续处理:

//If the model implements this method, it will be called at the end of 
//`+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`.
// If this method returns NO, the transform process will ignore this model.
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;

例子:
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
    //code...
    //dic[@"字段名"], 即可获取某个值, 自己处理后, 付给model。
    //时间戳转化为NSDate、求出文字高度...
    return YES;
}



3.对于后台的数据,如果需要处理“容器类”或者“大model包含小model”,直接参考GitHub原文做法更佳。
有个小demo可以看一下https://github.com/walkertop/YYModel—Demo

备注:
总之json与model与字典间的转化,都可以使用YYModel。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值