2018-12-12

iOS YYModel 使用方法

其实在研究这个库之前,市面上已经有很多类似的模型序列化成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

1User *user = [User yy_modelWithJSON:jsonString];

2NSLog(@"%@",user.ident[0].priceDate);

3// 将 Model 转换为 JSON 对象:

4NSDictionary *json = [user yy_modelToJSONObject];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.首先准备JSON及对象如下: 模型:Ident 模型:User (对象有包含关系时,在包含类的中需要申明一个m...
    ShineYangGod阅读 3,505评论 0 1
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,135评论 1 32
  • class VAE(object): def __init__(self, n_hidden=500, dim_z...
    AI_Finance阅读 269评论 0 1
  • 世界上转换速度最快、使用最简单方便的字典转模型框架 能做什么? MJExtension是一套字典和模型之间互相转换...
    今年27阅读 799评论 0 1
  • 词汇释义: 1.刷库:机器标注 2.元数据:关于数据的数据 3.pack:激光雷达存下来的数据,包括(视频、图片等...
    jinglongyi阅读 180评论 0 1