iOS Json转换模型库:YYModel

来源:互联网 发布:文艺知乎 编辑:程序博客网 时间:2024/05/22 06:58

iOS Json转换模型库:YYModel


iOS开发
来自: 增删改查 地址:http://simayang.com/archives/620.html#comment-61

其实在研究这个库之前,市面上已经有很多类似的模型序列化成JSON及反序列化库(如Mantle、MJExtension)了,推荐他只是因为他高端的性能和容错(错误对象类型赋值到属性时YYMODEL会尝试自动转换,避免Crash)以及低侵入(不需要你的MODEL类去继承某个基类、因为他是Category 方式来实现的)。作者号称对比性能如下:



接下来直接写一个小例子看如何使用:

1.首先准备JSON及对象如下:

{    "userName": "向阳",    "userPass": "xiang",    "age": 10,    "ident": [        {            "price": 100.56,            "priceDate": "1987-06-13 00:00:00"        },        {            "price": 100,            "priceDate": "1987-06-13"        }    ]}

模型:Ident

@interface Ident : NSObject@property(nonatomic,strong) NSNumber* price;@property(nonatomic,strong) NSDate* priceDate;@end#import "Ident.h"@implementation Ident@end

模型:User (对象有包含关系时,在包含类的中需要申明一个modelContainerPropertyGenericClass方法,并标明对应属性以及转换的对象类。如这里的User包含了Ident)

#import <Foundation/Foundation.h>#import "Ident.h"@interface User : NSObject@property(nonatomic,strong)NSString* userName;@property(nonatomic,strong)NSString* userPass;@property(nonatomic,strong)NSNumber* age;@property(nonatomic,strong)NSArray<Ident*>* ident;@end#import "User.h"#import "Ident.h"@implementation User// 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。+ (NSDictionary *)modelContainerPropertyGenericClass {    return @{@"ident" : [Ident class]};}@end

2.使用方法(yy_modelWithJSON、yy_modelToJSONObject)
yy_modelWithJSON:将 JSON (NSData,NSString,NSDictionary) 转换为 Model
yy_modelToJSONObject:将Model转换成NSDictionary以及NSArray

  User *user = [User yy_modelWithJSON:jsonString];  NSLog(@"%@",user.ident[0].priceDate);  // 将 Model 转换为 JSON 对象:  NSDictionary *json = [user yy_modelToJSONObject];
0 0