1.首先準(zhǔn)備JSON及對(duì)象如下:
{
"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 (對(duì)象有包含關(guān)系時(shí)铺峭,在包含類的中需要申明一個(gè)modelContainerPropertyGenericClass方法程拭,并標(biāo)明對(duì)應(yīng)屬性以及轉(zhuǎn)換的對(duì)象類歹袁。如這里的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
// 返回容器類中的所需要存放的數(shù)據(jù)類型 (以 Class 或 Class Name 的形式)沈矿。
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"ident" : [Ident class]};
}
@end
2.使用方法(yy_modelWithJSON溃斋、yy_modelToJSONObject)
yy_modelWithJSON:將 JSON (NSData,NSString,NSDictionary) 轉(zhuǎn)換為 Modelyy_modelToJSONObject:將Model轉(zhuǎn)換成NSDictionary以及NSArray
1 User *user = [User yy_modelWithJSON:jsonString];2 NSLog(@"%@",user.ident[0].priceDate);3 // 將 Model 轉(zhuǎn)換為 JSON 對(duì)象:4 NSDictionary *json = [user yy_modelToJSONObject];