iOS一点通

YYModel字典转模型的几种详细用法

2017-09-22  本文已影响4060人  MrRightGen
  1. YYModel 是ibireme写的一个 JSON 模型转换库,github 链接如下: https://github.com/ibireme/YYModel

常见用法包括:

1. JSON转模型

@interface NSObject (YYModel)
/**
 Creates and returns a new instance of the receiver from a json.
 This method is thread-safe.
 @param json  A json object in `NSDictionary`, `NSString` or `NSData`.
 @return A new instance created from the json, or nil if an error occurs.
 */
+ (nullable instancetype)modelWithJSON:(id)json;

2.字典转模型

/**
 @param dictionary  A key-value dictionary mapped to the instance's properties. 
 Any invalid key-value pair in dictionary will be ignored.
 遍历字典中的键值来匹配model中的属性, 无效的键值对会被忽略

 @discussion The key in `dictionary` will mapped to the reciever's property name,
 and the value will set to the property. If the value's type does not match the
 property, this method will try to convert the value based on these rules:
字典中的value类型跟model中的属性类型不一致时,按照以下规则处理:

     `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
      c number 类型, 如布尔值, 浮点型 整型转换成NSString,或者NSNumber
     `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
     日期格式转换成NSString 
     `NSString` -> NSURL.
     `NSValue` -> struct or union, such as CGRect, CGSize, ...
     `NSString` -> SEL, Class.
 */
+ (nullable instancetype)modelWithDictionary:(NSDictionary *)dictionary;

例子:

model :
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;

代码示例:
NSDictionary *dic = @{
                          @"name": @"WN",
                          @"age": @(99),
                          };
Model *model = [Model  modelWithDictionary:dic];

3. JSON数组转模型数组

@interface NSArray (YYModel)

/**
 Creates and returns an array from a json-array.
 This method is thread-safe.
 
 @param cls  The instance's class in array.
 @param json  A json array of `NSArray`, `NSString` or `NSData`.
              Example: [{"name","Mary"},{name:"Joe"}]
 
 @return A array, or nil if an error occurs.
 */
// cls 对应的是model类型  json 是一个数组
+ (nullable NSArray *)modelArrayWithClass:(Class)cls json:(id)json;

例子:

WNModel :
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;

代码示例:
NSArray *array = @[
{@"name": @"WN_1",
@"age": @(77)  
},
{@"name": @"WN_2",
@"age": @(88)  
},
{@"name": @"WN_3",
@"age": @(99)  
}              
                   ];
NSArray *modelArray = [NSArray  modelArrayWithClass:[WNModel class] json:array];

4.JSON字典转模型字典

@interface NSDictionary (YYModel)
/**
 @param cls  The value instance's class in dictionary.
 @param json  A json dictionary of `NSDictionary`, `NSString` or `NSData`.
 @return A dictionary, or nil if an error occurs.
 */
+ (nullable NSDictionary *)modelDictionaryWithClass:(Class)cls json:(id)json;

例子:

WNModel :
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;

代码示例:
NSDictionary *dic = @{
@"user1":
{@"name": @"WN_1",
@"age": @(77)  
},
@"user2":
{@"name": @"WN_2",
@"age": @(88)  
},
@"user3":
{@"name": @"WN_3",
@"age": @(99)  
}              
                   };
NSDictionary *modelDic= [NSDictionary  modelDictionaryWithClass:[WNModel class]  json : dic];

5. 字典里的属性名与模型里的属性名不一致

遵循<YYModel>协议 , 重写modelCustomPropertyMapper代理方法

 @discussion If the key in JSON/Dictionary does not match to the model's property name,
 Example:
    json: 
        {
            "n":"Harry Pottery",
            "p": 256,
            "ext" : {
                "desc" : "A book written by J.K.Rowling."
            },
            "ID" : 100010
        }
    model:
        @interface YYBook : NSObject
        @property NSString *name;
        @property NSInteger page;
        @property NSString *desc;
        @property NSString *bookID;
        @end
        
        @implementation YYBook
        + (NSDictionary *)modelCustomPropertyMapper {
            return @{@"name"  : @"n",
                     @"page"  : @"p",
                     @"desc"  : @"ext.desc",
                     @"bookID": @[@"id", @"ID", @"book_id"]};
        }
        @end
 
 @return A custom mapper for properties.
 */
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper;

6.黑名单 白名单

如果一个 Model 需要忽略某些属性,则可以通过实现 协议中的 modelPropertyBlacklist来返回属性名列表,YYModel 会在处理过程中忽略这些属性。

/**
 All the properties in blacklist will be ignored in model transform process.
 Returns nil to ignore this feature.

 @return An array of property's name.
 */
+ (nullable NSArray<NSString *> *)modelPropertyBlacklist;

如果一个 Model 只需要处理某些特性的属性,则可以通过实现 协议中的modelPropertyWhitelist 来返回属性名列表,YYModel 在处理中只会处理列表内的属性。

/**
 If a property is not in the whitelist, it will be ignored in model transform process.
 Returns nil to ignore this feature.
 
 @return An array of property's name.
 */
+ (nullable NSArray<NSString *> *)modelPropertyWhitelist;

以上6中方法基本就是我们会在工作中使用到的了...

插播一个硬广![想赚点零花钱的可以看看,微信扫二维码哈哈]


IMG_2867.PNG

)

上一篇 下一篇

猜你喜欢

热点阅读