IOS JSON轉換模型庫:YYMODEL


其實在研究這個庫之前,市面上已經有很多類似的模型序列化成JSON及反序列化庫(如Mantle、MJExtension)了,推薦他只是因為他高端的性能和容錯(錯誤對象類型賦值到屬性時YYMODEL會嘗試自動轉換,避免Crash)以及低侵入(不需要你的MODEL類去繼承某個基類、因為他是Category 方式來實現的)。作者號稱對比性能如下:

屏幕快照 2016-03-18 下午1.25.35

接下來直接寫一個小例子看如何使用:

1.首先准備JSON及對象如下:

 1 {
 2 "userName": "向陽",
 3 "userPass": "xiang",
 4 "age": 10,
 5 "ident": [
 6 {
 7 "price": 100.56,
 8 "priceDate": "1987-06-13 00:00:00"
 9 },
10 {
11 "price": 100,
12 "priceDate": "1987-06-13"
13 }
14 ]
15 }

 

模型:Ident

1 @interface Ident : NSObject
2 @property(nonatomic,strong) NSNumber* price;
3 @property(nonatomic,strong) NSDate* priceDate;
4 @end
5 #import "Ident.h"
6 @implementation Ident
7 @end

 

模型:User (對象有包含關系時,在包含類的中需要申明一個modelContainerPropertyGenericClass方法,並標明對應屬性以及轉換的對象類。如這里的User包含了Ident)

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

 

2.使用方法(yy_modelWithJSON、yy_modelToJSONObject)

yy_modelWithJSON:將 JSON (NSData,NSString,NSDictionary) 轉換為 Model
yy_modelToJSONObject:將Model轉換成NSDictionary以及NSArray

1 User *user = [User yy_modelWithJSON:jsonString];
2 NSLog(@"%@",user.ident[0].priceDate);
3 // 將 Model 轉換為 JSON 對象:
4 NSDictionary *json = [user yy_modelToJSONObject];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM