文章目录
JSONModel数据解析
关于JSONModel
JSONModel是json转model的第三方开源库。当我们向服务器发送一个请求之后,通过JSONModel把数据转成model中的属性就可以很方便的供给我们使用了
准备JSONModel
我们需要先加载JSONModel的库,这个操作和加载Masonry库时类似,在加载前先确定一下是否安装过JSONModel。
在终端输入
pod search JSONModel、
没问题后,新建项目去加载JSONModel
1. cd 项目目录
2. touch PodFile
3. 打开PodFile文件,在里面添加
platform :ios, '7.0'
target 'JSONModelB' do
pod 'JSONModel'
end
target后面为项目名称
4. 打开终端输入 pod install
准备就绪
前置工作
由于苹果官方已经默认不让开发者使用不安全的http通信协议了,而是建议开发者使用安全的https协议。所以我们要设置一下Xcode:
打开Info,在Information Property List后,将鼠标放上去有一个加号➕,新建一行App Transport Security Settings
之后右键该行,找到Add Row
添加Allow Arbitrary Loads,将后面的NO改为YES
这样就可以在项目中使用http协议来进行网络请求了
JSONModel的基本用法
基础用法
接下来我会用这个接口来进行演示:
https://news-at.zhihu.com/api/4/version/ios/2.3.0
第一步创建一个继承于JSONModel的类
我们点开链接可以看到:
不难发现双引号标出来了三个变量
“status”“msg”“latest”
我们首先要创建一个继承于JSONModel的类
我将其命名为testModel,这个类用来存放请求到的数据
我们在其.h头文件中可根据链接内容设置属性
#import "JSONModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface testModel : JSONModel
@property (nonatomic, assign) int status;
@property (nonatomic, copy) NSString* msg;
@property (nonatomic, copy) NSString* latest;
@end
NS_ASSUME_NONNULL_END
在其.m实现文件里添加
@implementation testModel
//+ (BOOL)propertyIsOptional:(NSString *)propertyName 作用是不想因为服务器的某个值没有返回(nil)就使程序崩溃, 我们会加关键字Optional,如果不想每一条属性都添加,我们也可以在.m文件中重写方法
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
return YES;
}
@end
加上这个可以避免出现错误
第二步使用网络请求到的数据将model初始化
//testModel.m
#import "ViewController.h"
#import "testModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view
NSString* string = [NSString stringWithFormat:@"https://news-at.zhihu.com/api/4/version/ios/2.3.0"];
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet] ];
NSURL* url = [NSURL URLWithString:string];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { testModel* country = [[testModel alloc] initWithData:data error:nil];
NSLog(@"%@",country);
}];
[dataTask resume];
}
@end
以下为请求到的数据
以上为请求比较简单的数据类型,并不涉及过多复杂的东西
集合,嵌套类型的数据
接下来我们试着来请求数据:
https://news-at.zhihu.com/api/4/news/latest
{"date":"20221009",
"stories":[{
"image_hue":"0x919399",
"title":"为什么饭店的大铁锅从来都不粘锅?",
"url":"https:\/\/daily.zhihu.com\/story\/9753797",
"hint":"知乎用户 · 4 分钟阅读",
"ga_prefix":"100907",
"images":["https:\/\/pic1.zhimg.com\/v2-68f0b605b2081be167479e9dbd6c41c2.jpg?source=8673f162"],
"type":0,
"id":9753797},
{"image_hue":"0x919199",
"title":"有哪些没个十斤脑洞都想不出来的发明?",
"url":"https:\/\/daily.zhihu.com\/story\/9753790",
"hint":"龙牙 · 2 分钟阅读",
"ga_prefix":"100907",
"images":["https:\/\/picx.zhimg.com\/v2-0c182ea5a3cd37a97ca4aa185d3ce927.jpg?source=8673f162"],
"type":0,
"id":9753790},
{"image_hue":"0xb3b3b3",
"title":"为什么没人培养一群克隆人来取代人们的工作呢?",
"url":"https:\/\/daily.zhihu.com\/story\/9753806",
"hint":"赵泠 · 1 分钟阅读",
"ga_prefix":"100907",
"images":["https:\/\/pic1.zhimg.com\/v2-be1bf8a86a1eaed3873f3d2cbbd2372b.jpg?source=8673f162"],
"type":0,
"id":9753806},
{"image_hue":"0x7c5a3f",
"title":"阿纳斯拉巨石是怎么被切开的?",
"url":"https:\/\/daily.zhihu.com\/story\/9753816",
"hint":"杨溢 · 4 分钟阅读",
"ga_prefix":"100907",
"images":["https:\/\/pica.zhimg.com\/v2-aeaf6adfc77e940a28be011c7ef5cd29.jpg?source=8673f162"],
"type":0,
"id":9753816},
{"image_hue":"0x2e3121",
"title":"自然界有吃了毒蘑菇不死的生物吗?",
"url":"https:\/\/daily.zhihu.com\/story\/9753822",
"hint":"郭昊天 · 1 分钟阅读",
"ga_prefix":"100907",
"images":["https:\/\/picx.zhimg.com\/v2-7b8063a8ab284839c9f1dba1d53a60e4.jpg?source=8673f162"],"type":0,"id":9753822},{"image_hue":"0x301f18","title":"瞎扯|如何正确地吐槽","url":"https:\/\/daily.zhihu.com\/story\/9753823","hint":"VOL.3018","ga_prefix":"100906","images":["https:\/\/picx.zhimg.com\/v2-f7d3a475ef8d26da0a40fd37d2f387f8.jpg?source=8673f162"],"type":0,"id":9753823}],
"top_stories":[{
"image_hue":"0x919399",
"hint":"作者 \/ 知乎用户",
"url":"https:\/\/daily.zhihu.com\/story\/9753797",
"image":"https:\/\/picx.zhimg.com\/v2-4fa5e85fe83822f33d039e4cacc77598.jpg?source=8673f162",
"title":"为什么饭店的大铁锅从来都不粘锅?",
"ga_prefix":"100907","type":0,"id":9753797},
{"image_hue":"0x121924",
"hint":"作者 \/ 瞻云",
"url":"https:\/\/daily.zhihu.com\/story\/9753754",
"image":"https:\/\/picx.zhimg.com\/v2-ef9dfc5cb5b221cf487d878f19133cd9.jpg?source=8673f162",
"title":"如果没有生殖隔离地球会变成什么样?",
"ga_prefix":"100807",
"type":0,
"id":9753754},
{"image_hue":"0xb37337","hint":"作者 \/ NikkiQ","url":"https:\/\/daily.zhihu.com\/story\/9753719","image":"https:\/\/picx.zhimg.com\/v2-b0f831d14f20465c7c1f6323db901b6b.jpg?source=8673f162","title":"小事 · 原生家庭非常幸福是怎样的体验?","ga_prefix":"100707","type":0,"id":9753719},{"image_hue":"0xb35f24","hint":"作者 \/ 知乎用户","url":"https:\/\/daily.zhihu.com\/story\/9753693","image":"https:\/\/picx.zhimg.com\/v2-c7e7f85ea3cc74c45e248610ea3696f0.jpg?source=8673f162","title":"小事 · 白头偕老才是最甜的爱情","ga_prefix":"100607","type":0,"id":9753693},{"image_hue":"0xb0a07b","hint":"作者 \/ 懂你","url":"https:\/\/daily.zhihu.com\/story\/9753636","image":"https:\/\/pica.zhimg.com\/v2-9f039adfd4319490d8bc80ad212a0275.jpg?source=8673f162","title":"小事 · 我想留住的那一刻","ga_prefix":"100407","type":0,"id":9753636}]}
可以看到,此数据有很多嵌套,我们需要根据每一个嵌套来写一个类,但是这并不意味着我们需要多个文件,我们只需要在一个文件里面把该有的都写上就行了
我们要解析的数据有一个字符串类的date属性,两个数组属性stories 和 top_Stories,里面存放了各种数据。我们创建stories 和 top_Stories的协议,并且创建stories 和 top_Stories两个类分别继承与JSONModel
如下代码
@protocol StoriesModel
@end
@protocol Top_StoriesModel
@end
#import "JSONModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface testModel : JSONModel
@property (nonatomic, copy) NSString* date;
@property (nonatomic, copy) NSArray<StoriesModel>* stories;
@property (nonatomic, copy) NSArray<Top_StoriesModel>* top_stories;
@end
@interface StoriesModel : JSONModel
@property (nonatomic, copy) NSString* url;
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* ga_prefix;
@property (nonatomic, copy) NSString* type;
@property (nonatomic, copy) NSString* hint;
@property (nonatomic, copy) NSString* image_hue;
@property (nonatomic, copy) NSArray* images;
@property (nonatomic, copy) NSString* id;
@end
@interface Top_StoriesModel : JSONModel
@property (nonatomic, copy) NSString* url;
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* ga_prefix;
@property (nonatomic, copy) NSString* type;
@property (nonatomic, copy) NSString* hint;
@property (nonatomic, copy) NSString* image_hue;
@property (nonatomic, copy) NSArray* images;
@property (nonatomic, copy) NSString* id;
@end
NS_ASSUME_NONNULL_END
同样的我们需要在.m实现文件里面添加
#import "testModel.h"
@implementation Top_StoriesModel
//+ (BOOL)propertyIsOptional:(NSString *)propertyName 作用是不想因为服务器的某个值没有返回(nil)就使程序崩溃, 可以加关键字Optional,如果不想每一条属性都添加,也可以在.m文件中重写方法
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
return YES;
}
@end
@implementation StoriesModel
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
return YES;
}
@end
@implementation testModel
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
return YES;
}
@end
和之前一样,还是防止错误
最后的viewdidload中将请求到的数据打印出来
#import "ViewController.h"
#import "testModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString* string = [NSString stringWithFormat:@"https://news-at.zhihu.com/api/4/news/latest"];
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:string];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
testModel* country = [[testModel alloc] initWithData:data error:nil];
NSLog(@"%@", country.stories[0]);
}];
[dataTask resume];
}
@end
得到如下结果
下划线自动转化为驼峰命名法
- 如果解析数据里有含有下划线的类型,我们可以设置属性的时候就设置成驼峰命名,然后实现一个方法,系统自定义把下划线字段解析为驼峰命名属性
- mapperFromUpperCaseToLowerCase
{
"order_id": 104,
"order_product" : @"Product#1",
"order_price" : 12.95
}
@interface OrderModel : BaseModel
@property (nonatomic, strong) NSString *orderId;
@property (nonatomic, assign) float orderPrice;
@property (nonatomic, strong) NSString *orderProduct;
@end
@implementation OrderModel
+ (JSONKeyMapper *)keyMapper {
return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
}
@end