ios利用josn解析(轉載)

openkk 12年前發布 | 27K 次閱讀 josn iOS開發 移動開發

json不必多說了,在手機開發中,客戶端和服務器端開發經常使用的數據交互模式。Iphone中利用json傳遞的數據,可以非常容易的展示到各個容器中。下面是一個最簡單的例子。效果如圖:

ios利用josn解析(轉載)

上面用到了json傳遞的數據,有關json部分,iphone sdk雖然沒有支持,但是第三方已經寫好了。

json 參考:http://code.google.com/p/json-framework/

下面是具體的代碼實現:

數據加載:

#import “MyDataSource.h”

#import “JSON.h”

@implementation MyDataSource

+ (NSDictionary *)fetchLibraryInformation

{

NSString *urlString = [NSString stringWithFormat:@"http://wangjun.easymorse.com/wp-content/video/hello.jison"];

NSURL *url = [NSURL URLWithString:urlString];

NSLog(@”fetching library data”);

return [self fetchJSONValueForURL:url];

}

+ (id)fetchJSONValueForURL:(NSURL *)url

{

NSString *jsonString = [[NSString alloc]initWithContentsOfURL:url

encoding:NSUTF8StringEncoding error:nil];

id jsonValue = [jsonString JSONValue];

[jsonString release];

return jsonValue;

}

@end

table數據展示:

#import “JSONTableTestViewController.h”

#import “MyDataSource.h”

@implementation JSONTableTestViewController

@synthesize myData;

- (void)viewDidLoad {

NSLog(@”加載數據);

myData = [[MyDataSource fetchLibraryInformation] retain];

}

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn’t have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren’t in use.

}

- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return [myData count]; //有多少個section,也就是幾家

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [[myData valueForKey:[[myData allKeys] objectAtIndex:section]] count];

//這里我們需要告訴UITableViewController每個section里面有幾個,也就是一家里面有幾口人

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @”Cell”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

reuseIdentifier:CellIdentifier] autorelease];

}

//上面的東西都是重復白給的,平時沒事不用想為什么,照抄就可以了

cell.textLabel.text = [[myData valueForKey:[[myData allKeys]objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

//這句看上去復雜,但是其實不過是在特定section里面找到對應的array

//然后在array中找到indexPath.row所在的內容

return cell;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

return [[myData allKeys] objectAtIndex:section];

//這里設置對應section的名字,很簡單allKey返回所有的鍵值為一個array,也就是張家李家

//然后用objectAtIndex: 來找出究竟是哪一個就可以了!

}

- (void)dealloc {

[myData release];

[super dealloc];

}

@end

源代碼見:http://easymorse.googlecode.com/svn/trunk/JSONTableTest/

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!