【iOS】—— JSONModel的使用

一. JSONModel的使用

1.什么是JSONModel

  • 做移动端开发,解析网络数据是必不可少的工作之一。iOS原生框架很早前就已经提供了将JSON数据直接映射成数组或者字典对象的方法,并且结合KVC,也可以将字典数据直接赋值给对象。但是这种方式十分不灵活,例如如果网络数据中的字段与我们数据模型中的字段不一致,某些网络数据的字段可能为nil等等都需要开发者单独的处理。使用JSOMModel可以十分方便的处理映射过程中的各种情况。

越来越多的移动应用更倾向于用JSON这种数据格式。一旦计划开发移动应用的并有与后台通信的需求,则要用JSON数据格式与服务器通信互相通信

  • JSONModel是用Objective-C写的开源库。它包含了接受发送解析JSON数据,用JSON数据驱动初始化你的类,还能够检验JSON和嵌套模型等功能。

2.怎样使用JSONModel

首先往文件中导入JSONModel库,具体方法和之前的Masonry的方法一致。

platform:ios,9.0’
target ‘JSONModel.new’ do
pod ‘JSONModel’
end

导入JSONModel库之后,创建一个继承于JSONModel的Model。这个类用来存放请求到的数据。
接下来对Model.h进行初始化:

#import "JSONModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface Model : JSONModel

@property (nonatomic, assign) int status;
@property (nonatomic, copy) NSString* msg;
@property (nonatomic, copy) NSString* latest;

@end

NS_ASSUME_NONNULL_END

然后再Model.m里面添加:

#import "Model.h"

@implementation Model
+ (BOOL) propertyIsOptional:(NSString *)propertyName {
    return  YES;
}
@end

3.进行网络请求数据

#import "ViewController.h"
#import "Model.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString* json = @"https://news-at.zhihu.com/api/4/version/ios/2.3.0";

    json = [json stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL* testURL = [NSURL URLWithString:json];

    NSURLRequest* testRequest = [NSURLRequest requestWithURL:testURL];
    NSURLSession* testSession = [NSURLSession sharedSession];
    NSURLSessionDataTask* testDataTask = [testSession dataTaskWithRequest:testRequest completionHandler:^(NSData* _Nullable data, NSURLResponse* _Nullable response, NSError* _Nullable error) {
       //以及自行创建好的类
        Model* country = [[Model alloc]initWithData:data error:nil];
        NSLog(@"%@", country);


    }];
    //任务启动
    [testDataTask resume];
}
@end

以下为请求到的数据:
在这里插入图片描述
以上为请求比较简单的数据类型,并不涉及过多复杂的东西

集合,嵌套类型的数据

对于复杂的数据,我们就需要根据每一个嵌套来写一个类,但是这并不意味着我们需要多个文件,我们只需要在一个文件里面把该有的都写上就行了。
我们要解析的数据有一个字符串类的date属性,两个数组属性stories 和 top_Stories,里面存放了各种数据。我们创建stories 和 top_Stories的协议,并且创建stories 和 top_Stories两个类分别继承与JSONModel。
如下代码:

#import "JSONModel.h"
@protocol StoriesModel
@end

@protocol Top_StoriesModel
@end

@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* title;
@property (nonatomic, copy) NSString* ga_prefix;
@property (nonatomic, copy) NSString* id;
@end

@interface Top_StoriesModel : JSONModel
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* ga_prefix;
@property (nonatomic, copy) NSString* id;
@end

同样的我们需要在.m实现文件里面添加

#import "TestModel.h"

@implementation TestModel
+ (BOOL) propertyIsOptional:(NSString *)propertyName {
    return  YES;
}
@end

@implementation StoriesModel
+ (BOOL) propertyIsOptional:(NSString *)propertyName {
    return  YES;
}
@end


@implementation Top_StoriesModel
+ (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* json = [[NSString alloc] init];
    json = @"https://news-at.zhihu.com/api/4/news/latest";
    json = [json stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL* testURL = [NSURL URLWithString:json];
    NSURLRequest* requst = [NSURLRequest requestWithURL:testURL];
    NSURLSession* testSession = [NSURLSession sharedSession];
    NSURLSessionDataTask* testDataTask = [testSession dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            TestModel* value = [[TestModel alloc] initWithData:data error:nil];
            NSLog(@"%@",value.date);
            NSLog(@"%@",value.stories[0]);
            NSLog(@"%@",value.top_stories[1]);
        } else {
            NSLog(@"请求失败");
        }
    }];

    [testDataTask resume];
}
@end

打印的数据如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值