加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

关于NSJSONSerialization

发布时间:2020-12-16 19:18:23 所属栏目:百科 来源:网络整理
导读:关于NSJSONSerialization,官方文档中有如下介绍: You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON. An object that may be converted to JSON must have the following properties:
关于NSJSONSerialization,官方文档中有如下介绍:
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
An object that may be converted to JSON must have the following properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString,NSNumber,NSArray,NSDictionary,or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
我们能利用NSJSONSerialization将JSON转换成Foundation对象,也能将Foundation对象转换成JSON,转换成JSON的对象必须具有如下属性:
顶层对象必须是NSArray或者NSDictionary
所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例
所有NSDictionary的key必须是NSString类型
数字对象不能是非数值或无穷
接下来看看如何使用,首先是如何生成JSON格式的数据:
我这里选用项目中的代码片段来进行简要介绍,以下显示了登陆请求JSON格式数据的生成
[cpp]
NSDictionary *registerDic = [NSDictionary dictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password",nil];
if ([NSJSONSerialization isValidJSONObject:registerDic]) {
NSError *error;
NSData *registerData = [NSJSONSerialization dataWithJSONObject:registerDic options:NSJSONWritingPrettyPrinted error:&error];
NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding]);
}
NSDictionary中的key就是json字符串中的key,object就是json字符串中的value,isValidJSONObject:方法是检测Foundation对象能否合法转换为JSON对象,dataWithJSONObject:options:error方法是将Foundation对象转换为JSON对象,参数NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
解析服务端返回的json格式数据:
[cpp]
NSDictionary *resultJSON = [NSJSONSerialization JSONObjectWithData:resultData options:kNilOptions error:&error];
获取返回字符串中key为status的value:
[cpp]
NSString *status = [resultJSON objectForKey:@"status"];
以上就简要的介绍了下NSJSONSerilazation的使用,不是很全面,以后有时间再深入详解一下。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读