IOS JsonModel的学习及使用
当我们从服务端获取到json数据后的时候,我们需要在界面上展示或者保存起来,下面来看下直接通过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 - 神奇的JSON数据建模框架 https://github.com/jsonmodel/jsonmodel
JSONModel可以快速创建智能数据模型。你可以在你的iOS,MacOS和watchOS和tvOS应用程序使用它。自动将JSON转成你的模型类,大大减少你需要编写的代码量。
见http://www.laileshuo.com/?p=669查看关于更改的详细信息。
pod 'JSONModel'
github "jsonmodel/jsonmodel"
假设你的JSON格式是这样的:
{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true }
@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
{
"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 *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
{
"id": 123,
"name": null,
"price": 12.95
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@property (nonatomic) NSNumber *uuid;
@end
{
"id": 123,
"name": null
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *customProperty;
@end
{
"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
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
@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
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@property (nonatomic) NSLocale *locale;
@property (nonatomic) NSNumber *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 ,以便下载最新代码进行研究使用。
学习记录,每天不停进步。