json和xml的普及个人觉得是为了简化阅读难度,以及减轻网络负荷,json和xml 数据格式在格式化以后都是一种树状结构,可以树藤摸瓜的得到你想要的任何果子。

而不格式化的时候json和xml 又是一个普普通通的字符串,在网络通信的时候也只需要请求一次,而不用每次为得到木一个值而重复的请求服务器或者目标主机,

json和xml 都采用 键 - 值 的形式来存放数据。

xml 使用: <键> 值 </键>

json 使用:  "键" : "值"

苹果公司提供了一个官方的json解析库 NSJSONSerialization

NSJSONSerialization  里面包含了两个方法来通过不同数据形式来解析json数据。

1、+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; //使用缓冲区数据来解析

2、+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error; // 使用文件流的形式来解析json

/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; /* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
*/
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;

解析json的步骤大概是,先把json字符串读取到缓冲区,然后使用NSJSONSerialization    里面的方法进行解析,根据不同json 格式可能返回的数据类型不一样,所以最好用 id 类型接。

eg:  id dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

在得到解析后的数据时,然后就一步一步 ,一个一个 键 - 值 的去寻找你想要的咚咚。

Eg 1 : 从本地文件中读取json数据,然后读取到缓冲区。

- (void)jsonParse{

    //初始化文件路径。
NSString* path = [[NSBundle mainBundle] pathForResource:@"nanjing" ofType:@"txt"];
//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//将字符串写到缓冲区。
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//解析json数据,使用系统方法 JSONObjectWithData: options: error:
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
//接下来一步一步解析。知道得到你想要的东西。
NSArray* arrayResult =[dic objectForKey:@"results"];
NSDictionary* resultDic = [arrayResult objectAtIndex:];
NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];
NSLog(@"geometryDic: %@, resultDic:%@",geometryDic,resultDic);
NSDictionary* locationDic = [geometryDic objectForKey:@"location"];
NSNumber* lat = [locationDic objectForKey:@"lat"];
NSNumber* lng = [locationDic objectForKey:@"lng"];
NSLog(@"lat = %@, lng = %@",lat,lng);
[jsonString release]; }

Eg 2 :使用网络路径来解析json,

- (void)jsonParse{

    //初始化网络路径。
NSString* path = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";
//初始化 url
NSURL* url = [NSURL URLWithString:path];
//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
//将字符串写到缓冲区。
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//解析json数据,使用系统方法 JSONObjectWithData: options: error:
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil]; //一下为自定义解析, 自己想怎么干就怎么干 NSArray* arrayResult =[dic objectForKey:@"results"];
NSDictionary* resultDic = [arrayResult objectAtIndex:];
NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];
NSLog(@"geometryDic: %@, resultDic:%@",geometryDic,resultDic);
NSDictionary* locationDic = [geometryDic objectForKey:@"location"];
NSNumber* lat = [locationDic objectForKey:@"lat"];
NSNumber* lng = [locationDic objectForKey:@"lng"];
NSLog(@"lat = %@, lng = %@",lat,lng);
[jsonString release]; }

Eg 3 :使用网络路径来解析json 。 使用NSURLRequest 和NSURLConnection 请求网络数据。

- (void)jsonParse{

    //初始化网络路径。
NSString* path = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";
//初始化 url
NSURL* url = [NSURL URLWithString:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
//将请求到的字符串写到缓冲区。
NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//解析json数据,使用系统方法 JSONObjectWithData: options: error:
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil]; //一下为自定义解析, 自己想怎么干就怎么干 NSArray* arrayResult =[dic objectForKey:@"results"];
NSDictionary* resultDic = [arrayResult objectAtIndex:];
NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];
NSLog(@"geometryDic: %@, resultDic:%@",geometryDic,resultDic);
NSDictionary* locationDic = [geometryDic objectForKey:@"location"];
NSNumber* lat = [locationDic objectForKey:@"lat"];
NSNumber* lng = [locationDic objectForKey:@"lng"];
NSLog(@"lat = %@, lng = %@",lat,lng); }

demo下载 :http://download.csdn.net/download/wsq724439564/6207829

Objective-C ,ios,iphone开发基础:JSON解析(使用苹果官方提供的JSON库:NSJSONSerialization)的更多相关文章

  1. Objective-C ,ios,iphone开发基础:使用GDataXML解析XML文档,(libxml/tree.h not found 错误解决方案)

    使用GDataXML解析XML文档 在IOS平台上进行XML文档的解析有很多种方法,在SDK里面有自带的解析方法,但是大多情况下都倾向于用第三方的库,原因是解析效率更高.使用上更方便 这里主要介绍一下 ...

  2. Objective-C ,ios,iphone开发基础:几个常用类-NSNumber

    2013-08-21 在Objective-C,包括int double float 等等再内的基础数据类型都不是一个类,所以就不能给它们发送消息,也就是说不能调用方法,那怎么办呢 ?Objectiv ...

  3. [置顶] Objective-C ,ios,iphone开发基础:UIAlertView使用详解

    UIAlertView使用详解 Ios中为我们提供了一个用来弹出提示框的类 UIAlertView,他类似于javascript中的alert 和c#中的MessageBox(); UIAlertVi ...

  4. Objective-C ,ios,iphone开发基础:UIAlertView使用详解

    UIAlertView使用详解 Ios中为我们提供了一个用来弹出提示框的类 UIAlertView,他类似于javascript中的alert 和c#中的MessageBox(); UIAlertVi ...

  5. Objective-C ,ios,iphone开发基础:快速实现一个简单的图片查看器

    新建一个single view 工程: 关闭ARC , 在.xib视图文件上拖放一个UIImageView  两个UIButton ,一个UISlider ,布局如图. 并为他们连线, UIImage ...

  6. Objective-C ,ios,iphone开发基础:http网络编程

    - (IBAction)loadData:(id)sender { NSURL* url = [NSURL URLWithString:@"http://162.105.65.251:808 ...

  7. Objective-C ,ios,iphone开发基础:3分钟教你做一个iphone手机浏览器

    第一步:新建一个Single View工程: 第二步:新建好工程,关闭arc. 第三步:拖放一个Text Field 一个UIButton 和一个 UIWebView . Text Field 的ti ...

  8. Objective-C ,ios,iphone开发基础:使用第三方库FMDB连接sqlite3 数据库,实现简单的登录

    第一步:下载第三方库,点击 连接 下载, 第二部:准备数据库:按照连接&中博客的步骤实现数据库, 数据库的设计大致如下表: id        username             pas ...

  9. Objective-C ,ios,iphone开发基础:ios数据库(The SQLite Database),使用终端进行简单的数据库操作

    SQLite  是一个轻量级的免费关系数据库.SQLite最初的设计目标是用于嵌入式系统,它占用资源非常少,在嵌入式设备中,只需要几百K的内存就够了,可以在(http://www.sqlite.org ...

随机推荐

  1. HDU-4742 Pinball Game 3D 三维LIS

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4742 题意:求3维的LIS.. 用分治算法搞得,参考了cxlove的题解.. 首先按照x排序,然后每个 ...

  2. 第二百五十六天 how can I 坚持

    今天比较闲,但是好累. 每天都会学到很多东西. 比如说,在没搞懂别人说这话之前,最好不要先表达自己的想法. 不宜妄自菲薄.不以物喜,不以己悲.hadoop. 睡觉.召生好速度啊,这么快就把我照片发给同 ...

  3. 查看解决Oracle对象锁住的问题

    在编译的一个存储过程的时候,对象可能由于被锁住而处于假的卡死状态,这个时候有的是因为,这个过程正在运行中,所以无法编译: 上次我遇到一次,我很清楚的确定这个过程没有运行,可以我就是无法编译,对象一直被 ...

  4. ocp 1Z0-051 106-140题解析

    106. Examine the data inthe LIST_PRICE and MIN_PRICE columns of the PRODUCTS table: LIST_PRICE MIN_P ...

  5. [iOS UI进阶 - 0] Quiartz2D

    A.简介 1. 需要掌握的 drawRect:方法的使用 常见图形的绘制:线条.多边形.圆 绘图状态的设置:文字颜色.线宽等 图形上下文状态的保存与恢复 图形上下文栈 1.基本图形绘制* 线段(线宽. ...

  6. ActiveMQ JMS 在发邮件中的使用

    ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久 ...

  7. 分析恶意驱动(进程启动apc注入dll)

    一.前言  用IDA也有好些时间了,以前就只会用F5功能玩无壳无保护的裸驱动,感觉太坑了,这两天就开始看网上大牛的逆向. 今天记录一下sudami曾经逆向过的fuck.sys.第一遍自己走的时候漏掉了 ...

  8. wikioi 3116 高精度练习之加法

    题目描述 Description 给出两个正整数A和B,计算A+B的值.保证A和B的位数不超过500位. 输入描述 Input Description 读入两个用空格隔开的正整数 输出描述 Outpu ...

  9. ADO.NET 快速入门(二):执行命令

    Commands发出针对数据库的数据存储动作.例如,你可以执行一条命令插入或者删除数据.获取更多从数据库移动数据相关的信息,请参考“Update a Database from a DataSet”. ...

  10. 参数对象Struts2中Action的属性接收参数

    题记:写这篇博客要主是加深自己对参数对象的认识和总结实现算法时的一些验经和训教,如果有错误请指出,万分感谢. Action中三种传递并接受参数: 1.  在Action添加成员属性接受参数 例如请求的 ...