轉自:
http://blog.csdn.net/chonbj/article/details/25982511
剛剛下午那會 弄了個 解析 xml demo的小例子,本想着json也挺複雜 弄還是 不弄,但是簡單的看了下 發現挺簡單,這個時候就猶豫了,要不寫到博客上來 ?
考慮了很久,還是寫上來吧,畢竟json用得太多了,而且算是自己的積累吧,畢竟剛開始學習IOS開發方面的知識,就當是鞏固了撒!
還是 先看個效果圖吧,如下!
接下來 看下工程目錄吧,其實並沒有必要,直接建立一個工程就行 ,算了,還是貼上來吧,如下:
工程目錄中有個 Notes.json 文件,該文件就是 要解析的json數據了 ,也截下圖吧,如下:
Ok ,以上準備完畢,就開始編碼了,在此之前故事版的內容 就和我上篇博客文章 IOS 解析xml 故事版 是一樣配置的,這裏就不在囉嗦了 ,首先看下 chonViewController.h文件,代碼如下:
- //
- // chonViewController.h
- // TestJson
- //
- // Created by choni on 14-5-16.
- // Copyright (c) 2014年 choni. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- @interface chonViewController : UITableViewController
- //保存數據列表
- @property(nonatomic,strong) NSMutableArray * listData;
- @end
與之對應的 chonViewController.m文件 代碼如下:
- //
- // chonViewController.m
- // TestJson
- //
- // Created by choni on 14-5-16.
- // Copyright (c) 2014年 choni. All rights reserved.
- //
- #import "chonViewController.h"
- @interface chonViewController ()
- @end
- @implementation chonViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- NSString * path = [[NSBundle mainBundle]pathForResource:@"Notes" ofType:@"json" ];
- NSData * jsonData = [[NSData alloc] initWithContentsOfFile:path];
- NSError * error ;
- id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
- if (!jsonObj || error) {
- NSLog(@"JSON解析失敗");
- }
- self.listData = [jsonObj objectForKey:@"Record"];
- }
- #pragma mark - tableView
- -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
- return 1;
- }
- -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
- return self.listData.count;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
- NSMutableDictionary * dict = self.listData[indexPath.row];
- cell.textLabel.text = [dict objectForKey:@"Content"];
- cell.detailTextLabel.text = [dict objectForKey:@"CDate"];
- return cell ;
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- }
- @end
Ok , 現在就可以編譯運行的程序了 ,但是有個主意的地方 :
1.因爲使用 NSJSONSerialization 實現json解碼,要確定你得項目使用IOS 5 SDK 纔可以
2. 其他的就沒有什麼了,介紹下NSJSONSerialization的類方法吧
1)NSJSONReadingMutableContaines ,指定解析返回的是可變的數組或字典 ,這個方法還是比較使用的,因爲如果json數據需要改,不用管撒
2)NSJSONReadingMutableLeaves ,指定葉節點是可變的字符串
3) NSJSONReadingAllowFragments , 指定頂級節點可以部署數組或字典
另,json是輕量級的數據交換格式。。。。什麼的,去你大爺的,但在應用開發的時候 優選考慮json 而不是xml ,xml 最先考慮的應當是TBXML,上篇博客提到過,json 最先
考慮NSJSONSerialization 。