媒介:對辦事器要求以後,前往給客戶真個數據,普通都是JSON格局或許XmlRss/ target=_blank class=infotextkey>Xml格局(文件下載除外)


本篇隨意先講授JSON解析。
注釋:
關於JSON:
JSON是一種輕量級的數據格局,普通用於數據交互JSON的格局很像Objective-C中的字典和數組:{"name":"jack","age":10}
彌補:
尺度的JSON格局的留意點:key必需用雙引號。(然則在Java中是單引號)
JSON-OC的轉換對比表

個中:null--前往OC裡的NSNull類型
應用:
在JSON解析計劃有許多種,然則(蘋果原生的)NSJSONSerialization機能最好
反序列化(JSON --> OC對象),上面示例解析成字典對象

序列化(OC對象 --> JSON),留意字典的值不克不及傳nil,然則可以傳[NSNull null]

其實不是一切的類型都是可以轉為JSON的
以下是蘋果官方劃定:

我們再來看個實例:
#import "MainViewController.h"
#import "Video.h"
#define kBaseURL @"http://192.168.3.252/~apple"
@interface MainViewController ()
@property (strong, nonatomic) NSArray *dataList;
@property (weak, nonatomic) UITableView *tableView;
@end
@implementation MainViewController
class="p1">
"412158" snippet_file_name="blog_20140630_1_3481337" name="code" class="objc">
#pragma mark 實例化視圖
- (void)loadView
{
self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
//1 tableview
CGRect frame = self.view.bounds;
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 44) style:UITableViewStylePlain];
//1)數據源
[tableView setDataSource:self];
//2)署理
[tableView setDelegate:self];
//)設置表格高度
[tableView setRowHeight:80];
[self.view addSubview:tableView];
self.tableView = tableView;
//toolBar
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, tableView.bounds.size.height, 320, 44)];
[self.view addSubview:toolBar];
//添加toolbar按鈕
UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:@"load json" style:UIBarButtonItemStyleDone target:self action:@selector(loadJson)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"load XmlRss/ target=_blank class=infotextkey>Xml" style:UIBarButtonItemStyleDone target:self action:@selector(loadXml)];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolBar setItems:@[item3, item1, item3, item2, item3]];
}
#pragma mark -uitableview數據源辦法 關於uitableview上面這兩個辦法是必需完成的。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataList.count;
}
//每填充一行都挪用一次這個辦法。曉得界面上的一切行都填充終了。,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//應用可充用標示符查詢可重用單位格
static NSString *ID = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//設置單位格內容
Video *v = self.dataList[indexPath.row];
cell.textLabel.text = v.name;
cell.detailTextLabel.text = v.teacher;
//加載圖片
//1)同步加載收集圖片,同步辦法認為這這些指令在完成之前,後續指令都沒法履行。
//留意:在開辟收集運用時,不要應用同步辦法加載圖片,不然會嚴重影響用戶體驗
// NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL];
// NSURL *imageUrl = [NSURL URLWithString:imagePath];
// NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
// UIImage *image = [UIImage imageWithData:imageData];
//
// //2)異步加載收集圖片
// //收集銜接自己就有異步敕令 sendAsync
// [cell.imageView setImage:image];
//假如緩存圖象不存在
if (v.cacheImage == nil) {
//應用默許圖象占位,即可以或許包管有圖象,又可以或許包管有處所。
UIImage *image = [UIImage imageNamed:@"user_default.png"];
[cell.imageView setImage:image]; //應用默許圖象占位
//開啟異步銜接,加載圖象,由於加載完成以後,須要刷新對應的表格航
[self loadImageAsyncWithIndexPath:indexPath];
}else
{
[cell.imageView setImage:v.cacheImage];
}
//[self loadImageAsyncWithUrl:imageUrl imageView:cell.imageView];
return cell;
}
#pragma mark 異步加載收集圖片
//因為uitableview是可重用的,為了不用戶疾速頻仍刷新表格,形成數據抵觸,不克不及直接將uiimageview傳入異步辦法
//准確的處理辦法是:將表格行的indexpath傳入異步辦法,加載完成圖象今後,直接刷新指定的行。
- (void)loadImageAsyncWithIndexPath:(NSIndexPath *)indexPath
{
Video *v = self.dataList[indexPath.row]; //掏出以後要填充的行
NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL];
NSURL *imageUrl = [NSURL URLWithString:imagePath];
//NSLog(@"%@ %@", url, imageView);
//1 request
NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
//2 connection sendasync異步要求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//UIImage *image = [UIImage imageWithData:data];
//[imageView setImage:image];
//將收集數據保留至緩存圖象。
v.cacheImage = [UIImage imageWithData:data];
//刷新表格
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}];
}
#pragma mark 處置json數據
- (void)handlerJSONData:(NSData *)data
{
//json文件中的[]表現一個數據。
//反序列化json數據
//第二個參數是解析方法,普通用NSJSONReadingAllowFragments
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", array); //json解析今後是nsarray格局的數據。
//提醒:假如開辟收集運用,可以將反序列化出來的對象,保留至沙箱,以便後續開辟應用。
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0]stringByAppendingPathComponent:@"json.plist"];
[array writeToFile:path atomically:YES]; //把array外面的數據寫入沙箱中的JSPn.plist中。
//給數據列表賦值
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
Video *video = [[Video alloc]init];
//給video賦值
[video setValuesForKeysWithDictionary:dict];
[arrayM addObject:video];
}
self.dataList = arrayM;
//刷新表格
[self.tableView reloadData];
NSLog(@"%@", arrayM); //這句話將挪用video外面的description和nsarray+log外面的descriptionWithLocale
}
#pragma mark 加載json
- (void)loadJson
{
NSLog(@"load json");
//從web辦事器加載數據
NSString *str = @"http://www.百度.com?format=json"; //這裡是亂寫的
//提醒:NSData自己具有同步辦法,然則在現實開辟中,不要應用次辦法
//在應用NSData的同步辦法時,沒法指定超不時間,假如辦事器銜接不正常,會影響用戶體驗。
//NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
//簡歷NSURL
NSURL *url = [NSURL URLWithString:str];
//樹立NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
//樹立NSURLConnect的同步辦法加載數據
NSURLResponse *response = nil;
NSError *error = nil;
//同步加載數據
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//毛病處置
if (data != nil) {
//上面這兩句話自己沒有甚麼意義,僅用於跟蹤調試。
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
//在處置收集數據的時刻,不要將NSData轉換成nsstring。
[self handlerJSONData:data];
}else if (data == nil && error == nil){
NSLog(@"空數據");
}else
{
NSLog(@"%@", error.localizedDescription);
}
}
#pragma mark 加載xml
- (void)loadXML
{
NSLog(@"load xml");
}
//- (void)viewDidLoad
//{
// [super viewDidLoad];
//}
@end
【iOS開辟應用JSON解析收集數據】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!