IOS JsonModel的学习及使用
当我们从服务端获取到json数据后的时候,我们需要在界面上展示或者保存起来,下面来看下直接通过NSDictionary取出数据的情况。
NSDictionary直接取出数据的诟病。
NSString *name = [self.responseObj objectForKey:@"name"];
NSString *gender = [self.responseObj objectForKey:@"gender"];
NSString *sign = [self.responseObj objectForKey:@"sign"];
NSString *avatar = [self.responseObj objectForKey:@"avatar"];
NSString *phone = [self.responseObj objectForKey:@"phone"];
NSString *token = [self.responseObj objectForKey:@"token"];
从以上的代码,我们能够看出,取出数据相当繁琐的。为了防止显示及出现crash等问题,还需要判断值的nil,null,类型等情况的出现。
所以我们需要使用到JSONModel。
简介JSONModel
JSONModel - 神奇的JSON数据建模框架 https://github.com/jsonmodel/jsonmodel
JSONModel可以快速创建智能数据模型。你可以在你的iOS,MacOS和watchOS和tvOS应用程序使用它。自动将JSON转成你的模型类,大大减少你需要编写的代码量。
见http://www.laileshuo.com/?p=669查看关于更改的详细信息。
(图片来源于网络)
JSONModel安装(Installation)
- 使用CocoaPods安装,在podfile,添加一下内容,之后使用pod update更新
pod 'JSONModel'
- 使用Carthage安装
github "jsonmodel/jsonmodel"
JSONModel使用手册(Manual)
- 下载JSONModel库
- 复制JSONModel子文件夹到您的Xcode项目
- 添加SystemConfiguration.framework库
JSONModel基础用法(Basic Usage)
假设你的JSON格式是这样的:
{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true }
- 创建一个JSONModel的子类
- 在.h头文件中声明一些以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中的key的value值为CountryModel的id,country,dialCode,isInEurope的属性赋值。并且自动匹配相遇的类型。
实例
自动根据名称映射
{
"id": 123,
"name": "Product name",
"price": 12.95
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end
模型嵌套 (模型包含其他模型)
{
"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
模型集合collections
{
"orderId": 104,
"totalPrice": 103.45,
"products": [
{
"id": 123,
"name": "Product #1",
"price": 12.95
},
{
"id": 137,
"name": "Product #2",
"price": 82.95
}
]
}
@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的后尖括号包含的协议。这是不一样的目标C泛型系统。它们不是相互排斥的,而是为JSONModel工作,该协议必须到位。
嵌套键映射
{
"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
自动映射到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
可选属性Optional (就是说这个属性可以为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
忽略属性 Ignored (就是JSONModel完全忽略这个属性)
{
"id": 123,
"name": null
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString <Ignore> *customProperty;
@end
设置标量类型可选optional
{
"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
将model转成json
ProductModel *pm = [ProductModel new];
pm.name = @"Some Name";
// convert to dictionary
NSDictionary *dict = [pm toDictionary];
// convert to json
NSString *string = [pm toJSONString];
特定类型数据转换
@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
自定义 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
自定义验证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
如果您需要查看详情JSONModel的使用请访问https://github.com/jsonmodel/jsonmodel ,以便下载最新代码进行研究使用。
学习记录,每天不停进步。