博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【转】NSJSONSerialization解析JSON数据
阅读量:7176 次
发布时间:2019-06-29

本文共 2140 字,大约阅读时间需要 7 分钟。

JSON->NSData

1 - (IBAction)touchWriteButton:(id)sender {
2 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 3 [dictionary setValue:@"Anthony" forKey:@"First Name"]; 4 [dictionary setValue:@"Robbins" forKey:@"Last Name"]; 5 [dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"]; 6 NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:@"Anthony's Son 1", @"Anthony's Daughter 1", @"Anthony's Son 2", @"Anthony's Son 3", @"Anthony's Daughter 2", nil]; 7 [dictionary setValue:arrayOfAnthonysChildren forKey:@"children"]; 8 NSError *error = nil; 9 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; 10 if (error) { 11 NSLog(@"dic->%@",error); 12 } 13 [dictionary release]; 14 BOOL succeed = [jsonData writeToFile:JSON_PATH atomically:YES]; 15 if (succeed) {
16 NSLog(@"Save succeed"); 17 }else {
18 NSLog(@"Save fail"); 19 } 20 }
 
NSData->JSON
1 - (IBAction)touchReadButton:(id)sender {  2       NSData *jsonData = [[NSData alloc] initWithContentsOfFile:JSON_PATH];     /* Now try to deserialize the JSON object into a dictionary */  3       NSError *error = nil;  4       id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];  5      if (jsonObject != nil && error == nil){
6 NSLog(@"Successfully deserialized..."); 7 if ([jsonObject isKindOfClass:[NSDictionary class]]){
8 NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject; 9 NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary); 10 } else if ([jsonObject isKindOfClass:[NSArray class]]){
11 NSArray *deserializedArray = (NSArray *)jsonObject; 12 NSLog(@"Dersialized JSON Array = %@", deserializedArray); 13 } else {
14 NSLog(@"An error happened while deserializing the JSON data."); 15 } 16 } 17 [jsonData release]; 18 }

 

转载地址:http://mmfzm.baihongyu.com/

你可能感兴趣的文章
macos mojave 安装brew 出错总结
查看>>
HDU 1667 Nested Dolls
查看>>
SQL数据库类型
查看>>
XGPush集成(信鸽集成)demo
查看>>
结构化异常处理 读书笔记
查看>>
性能优化3--数据库优化
查看>>
JavaScript知识点回顾
查看>>
关于浏览器兼容处理的几种方式
查看>>
第一个Asp.net小项目,主页写了下后台代码
查看>>
(推荐使用)SpringMVC注解,基本配置
查看>>
ORA-12547: TNS:lost contact+oracle 开启监听失败
查看>>
软件工程结对作业01(四则运算网页版)
查看>>
解决开机自动调用脚本失败的问题
查看>>
LoadRunner监控图表与配置(二)监控运行状况和交易状况
查看>>
创建对象的几种方式
查看>>
《鸟哥的Linux私房菜》读书笔记--第0章 计算机概论 硬件部分
查看>>
02、学PHP可以干什么
查看>>
iOS - WXPay 微信支付
查看>>
tcp/ip高效编程总结
查看>>
hdu 4739 Zhuge Liang's Mines 2013 ACM/ICPC Asia Regional Hangzhou Online
查看>>