【OC】JSONModel基本使用

这篇博客介绍了如何利用JSONModel库在Objective-C中轻松地将网络请求的JSON数据转换为数据模型,包括基本使用步骤、网络请求数据转换以及处理集合和嵌套型数据的方法。示例展示了从JSON到模型的映射过程,以及如何初始化和验证数据模型。
摘要由CSDN通过智能技术生成

JSONModel是一个库,让我们能快速创建智能数据模型。

基本使用

假设我有这样一个JSON数据

{
   
    "country":"Germany",
    "dialCode": 49,
    "isInEurope":YES
}
  1. 创建一个新的Objective-C类,并使其继承JSONModel类。
  2. 声明与JSON键同名的属性。
#import "JSONModel.h"


NS_ASSUME_NONNULL_BEGIN

@interface CountryModel : JSONModel

@property (nonatomic, copy) NSString* country;
@property (nonatomic, copy) NSString* dialCode;
@property (nonatomic, assign) BOOL isInEurope;

@end

NS_ASSUME_NONNULL_END
  1. 初始化数据模型。
NSError* error = nil;

CountryModel* countryModel = [[CountryModel alloc] initWithDictionary:dict error:error];

如果JSON的验证通过你在你的模型中填充的JSON所有相应的属性。JSONModel也将尝试将尽可能多的数据转换为您所期望的类型,在这个例子中,dialCode将数字转换成字符串。

网络请求数据转换模型

接口:https://news-at.zhihu.com/api/4/version/ios/2.3.0

返回数据示例:

{
   
"status":1,
"msg":"【更新内容】\r\n\r\n★ 多图有标记 流量壕忽略\r\n★ 出门前离线 没网也能看\r\n★ 喜欢请好评 不喜快吐槽\r\n★ 萌妹工程师 邮箱在下面\r\nmua@zhihu.com\r\n(一般人我们不告诉他)",
"latest":"2.5"
}

Objective-C类:

@interface TestModel : JSONModel
@property (nonatomic, assign) int status;
@property (nonatomic, copy) NSString* msg;
@property (nonatomic, copy) NSString* latest;
@end

请求数据:

- (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 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值