原文网址:http://blog.csdn.net/enuola/article/details/7903632
作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式。
有的json代码格式比较混乱,可以使用此“http://www.bejson.com/”网站来进行JSON格式化校验( 点击打开链接 )。此网站不仅可以检测Json代码中的错误,而且可以以视图形式显示json中的数据内容,很是方便。
从IOS5开始,APPLE提供了对json的原生支持(NSJSONSerialization),但是为了兼容以前的ios版本,可以使用第三方库来解析Json。
本文将介绍 TouchJson、 SBJson 、JSONKit 和 iOS5所支持的原生的json方法 ,解析国家气象局API,TouchJson和SBJson需要下载他们的库
TouchJson包下载: http://download.csdn.net/detail/enuola/4523169
SBJson 包下载: http://download.csdn.net/detail/enuola/4523177
JSONKit包下载:http://download.csdn.net/detail/enuola/4523160
下面的完整程序源码包下载:http://download.csdn.net/detail/enuola/4523223
国家气象局提供的天气预报接口
接口地址有三个:
http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html
http://m.weather.com.cn/data/101010100.html
第三接口信息较为详细,提供的是6天的天气,关于API所返回的信息请见 开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供) ,全国各城市对应这一个id号,根据改变id好我们就可以解析出来各个城市对应天气;
下面介绍四种方法解析JSON:
首先建立一个新的工程,(注意不要选择ARC机制)添加如下控件:
如上图所示。下面展出程序代码:
文件 ViewController.h 中:
(1)使用 TouchJSon 解析方法:(需导入包:#import "TouchJson/JSON/CJSONDeserializer.h")
我们选择的测试对象包含下面的这几个框架,其中NSJSONSerialization是iOS5系统新增的JSON解析的API,需要iOS5的环境,如果您在更低的版本进行测试,应该屏蔽相应的代码调用。
- [SBJSON (json-framework)](http://code.google.com/p/json-framework/)
- [TouchJSON (from touchcode)](http://code.google.com/p/touchcode/)
- [YAJL (objective-C bindings)](http://github.com/gabriel/yajl-objc)
- [JSONKit](https://github.com/johnezang/JSONKit)
- [NextiveJson](https://github.com/nextive/NextiveJson)
-[NSJSONSerialization](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946)
我们选择了四个包含json格式的数据的文件进行测试。每一个文件进行100的解析动作,对解析的时间进行比较。
.....
测试的结果显示,系统的API的解析速度最快,我们在工程项目中选择使用,也是应用较为广泛的SBJSON的解析速度为倒数第二差,令我大跌眼镜。
与系统API较为接近的应该是JSONKit。
这里没有对API的开放接口和使用方式进行比较,若单纯基于以上解析速度的测试:
1:iOS5应该选择系统的API进行
2:不能使用系统API的应该选择JSONKit