MJExtension
长话短说下面我们通过一个列子来看下怎么使用
1、 先把框架拉进去你的项目
2、 首先我这次用到的json最外层是一个字典,根据数据的模型我们可以把这个归类为字典中有数组,数组中还有其他 针对于这种情况 我需要建立两个数据模型 一个是要获取其中的数组 另一个数组中的的City元素
代码后面讲解思路
#import <Foundation/Foundation.h>
@interface NSCity : NSObject
@property (nonatomic,strong)NSString *city;
@property (nonatomic,strong)NSString *h5_url;
@property (nonatomic,strong)NSNumber* ID;
@property (nonatomic,strong)NSString *deal_url;
@end
// NSCity.m
// MJExtension example
//
// Created by tareba on 15/12/18.
// Copyright © 2015年
tanada. All rights reserved.
//
#import "NSCity.h"
@implementation NSCity
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if ([key isEqualToString:@"id"])
{
self.ID=value;
}
}
@end
#import <Foundation/Foundation.h>
@interface NSDeals : NSObject
@property (nonatomic,strong)NSMutableArray *deals;
@end
#import "NSDeals.h"
#import "MJExtension.h"
@implementation NSDeals
下面的方法是关键
、、
+ (NSDictionary *)mj_objectClassInArray
{
return @{
@"deals" :
@"NSCity",
};
}
@end
#import "ViewController.h"
#import "MJExtension.h"
#import "NSCity.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *request =[NSURLRequest
requestWithURL:[NSURL
URLWithString:@"http://api.dianping.com/v1/deal/find_deals?appkey=4123794720&category=%E7%BE%8E%E9%A3%9F&city=%E9%83%91%E5%B7%9E®ion=%E9%87%91%E6%B0%B4%E5%8C%BA&sort=2&sign=FB7A61EB742A4B697B666985348614C7A8F763A3"]];
NSURLSession *seesion = [NSURLSession
sharedSession];
NSURLSessionDataTask *task =[seesion
dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dic=
[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:nil];
NSDeals *result =[NSDeals
mj_objectWithKeyValues:dic];
for (NSCity *city in
result.deals) {
NSLog(@"%lu",(unsigned long)result.deals.count);
NSLog(@"%@",city.deal_url);
}
}];
[task resume];
}
@end
这个方法是将json数据的层级关系,变成属性关系,下一层成为了上一层的属性,然后通过属性直接姐可以访问了。至于关键字成为属性,由于时间紧迫未来的及验证是否和平时利用
setvaluefor undefinekey的法解决是否相同 待验证后会尽快修改