你的位置:首页 > 软件开发 > 操作系统 > iOS JsonModel 的使用

iOS JsonModel 的使用

发布时间:2016-04-12 23:00:09
本文转自:http://blog.csdn.net/smking/article/details/40432287 下面讲一下JSONModel的使用方法。 @inteface MyModel : JSONModel 1. 使用JSONModel时,不需要额外去检查所 ...

iOS JsonModel 的使用

 

本文转自:http://blog.csdn.net/smking/article/details/40432287

 

下面讲一下JSONModel的使用方法。 

@inteface MyModel : JSONModel

 

1. 使用JSONModel时,不需要额外去检查所要的服务器属性是否有返回。JSONModel的initWithDictionary方**自动去进行检查并处理。

 

2. 有效性检查,如果指定的服务器返回的某个字段没有返回,而且又是必须的, 像下面这样写,则会抛出异常。

 

//this property is required

@property (strong, nonatomic) NSString* string;

因为默认这个值是必须的。

 

 

一般情况下,我们不想因为服务器的某个值没有返回就使程序崩溃, 我们会加关键字Optional.

 

//this one's optional

@property (strong, nonatomic) NSNumber<Optional>* number;

 

 

3. 原子数据, 之前可能是如下面这样操作数据

 

if (jsonDict[@"name"])

labelName.text = jsonDict[@"name"];

else

[self showErrorMessageAndBailout];

 

这段代码会使得jsonDict[@"name"], 会被读取,然后进行有效性判断,最后再被使用。 换句话来说,这里使用了三次, 而如果某些情况下,使用一次就已经出错,但却无法阻止它接下来的连续出错。

 

而如果使用JSONModel的属性,则只会保证上面只使用一次,就可以进行有效性的判断以及使用。(其实上面也可以做到,只需要把这个值取出来,存下来接着使用却可,但是代码会稍显麻烦)

同时读取一批数据如下面代码:

简单模型如下:

 

SimpleModel* model = [[SimpleModel alloc] initWithString:@"...json here..." error:nil];

 然后再定义模型:

原标题:iOS JsonModel 的使用

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。