JSONModel的使用
2017-05-26 本文已影响0人
夏天的风_song
一、引入
1、CocoaPods
pod 'JSONModel'
2、Carthage
github "jsonmodel/jsonmodel"
3、手动导入
- 下载JSONModel仓库
- 把JSONModel下的文件导入到你的工程
- 将SystemConfiguration.framework链接到你的应用程序中
二、用法
1、基本用法
假设说你有个这个样子的JSON
{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true }
- 首先为你的数据模型建一个JSON的子类
- 在你数据模型的头文件里,用JSON的key值作为属性的名字
@interface CountryModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *country;
@property (nonatomic) NSString *dialCode;
@property (nonatomic) BOOL isInEurope;
@end
你不需要在.m文件里写任何东西
- 用数据实例化你的模型类
NSError *error;
CountryModel *country = [[CountryModel alloc] initWithString:myJson error:&error];
如果JSON的验证通过。您的模型中包含所有相应的属性,从JSON中填充。JSONModel还将尝试将尽可能多的数据转换为您期望的类型。在上面的例子中,它将:
- 转换id从字符串(以JSON)到int你的类
- 复制该country值
- 将dialCode数字(在JSON中)转换为NSString值
- 复制该isInEurope值
三、示例
1、自动名称映射
{
"id": 123,
"name": "Product name",
"price": 12.95
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end
2、模型嵌套(模型包含其它模型)
{
"orderId": 104,
"totalPrice": 13.45,
"product": {
"id": 123,
"name": "Product name",
"price": 12.95
}
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic) ProductModel *product;
@end
3、模型集合
{
"orderId": 104,
"totalPrice": 103.45,
"products": [
{
"id": 123,
"name": "Product #1",
"price": 12.95
},
{
"id": 137,
"name": "Product #2",
"price": 82.95
}
]
}
@class ProductModel;
@protocol ProductModel <NSObject>
@end
@protocol ProductModel;
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic) NSArray <ProductModel> *products;
@end
注意:NSArray后的<>包含一个协议。这与OC泛型系统不同。它们不是相互排斥的,但是对于JSONModel来说,协议必须到位。
4、嵌套键映射
{
"orderId": 104,
"orderDetails":
{
"name": "Product #1",
"price": {
"usd": 12.95
}
}
}
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *productName;
@property (nonatomic) float price;
@end
@implementation OrderModel
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
@"id": @"orderId",
@"productName": @"orderDetails.name",
@"price": @"orderDetails.price.usd"
}];
}
@end
5、映射到snake_case(去掉中间的下划线)
{
"order_id": 104,
"order_product": "Product #1",
"order_price": 12.95
}
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) NSString *orderProduct;
@property (nonatomic) float orderPrice;
@end
@implementation OrderModel
+ (JSONKeyMapper *)keyMapper
{
return [JSONKeyMapper mapperForSnakeCase];
}
@end
6、可选属性(即可以缺少或为null)
{
"id": 123,
"name": null,
"price": 12.95
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString <Optional> *name;
@property (nonatomic) float price;
@property (nonatomic) NSNumber <Optional> *uuid;
@end
7、被忽略的属性(即JSONModel完全忽略它们)
{
"id": 123,
"name": null
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString <Ignore> *customProperty;
@end
8、使标量类型可选
{
"id": null
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@end
@implementation ProductModel
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
if ([propertyName isEqualToString:@"id"])
return YES;
return NO;
}
@end
9、将模型导出为NSDictionary或JSON
ProductModel *pm = [ProductModel new];
pm.name = @"Some Name";
// convert to dictionary
NSDictionary *dict = [pm toDictionary];
// convert to json
NSString *string = [pm toJSONString];
10、自定义数据转换
@interface JSONValueTransformer (CustomNSDate)
@end
@implementation JSONValueTransformer (CustomTransformer)
- (NSDate *)NSDateFromNSString:(NSString *)string
{
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = APIDateFormat;
return [formatter dateFromString:string];
}
- (NSString *)JSONObjectFromNSDate:(NSDate *)date
{
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = APIDateFormat;
return [formatter stringFromDate:date];
}
@end
11、自定义getters/setters
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@property (nonatomic) NSLocale *locale;
@end
@implementation ProductModel
- (void)setLocaleWithNSString:(NSString *)string
{
self.locale = [NSLocale localeWithLocaleIdentifier:string];
}
- (void)setLocaleWithNSDictionary:(NSDictionary *)dictionary
{
self.locale = [NSLocale localeWithLocaleIdentifier:dictionary[@"identifier"]];
}
- (NSString *)JSONObjectForLocale
{
return self.locale.localeIdentifier;
}
@end
12、自定义JSON验证
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@property (nonatomic) NSLocale *locale;
@property (nonatomic) NSNumber <Ignore> *minNameLength;
@end
@implementation ProductModel
- (BOOL)validate:(NSError **)error
{
if (![super validate:error])
return NO;
if (self.name.length < self.minNameLength.integerValue)
{
*error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil];
return NO;
}
return YES;
}
@end