以下大家友情支持一下:
做了一个产品,需要人气支持一下,android和iphone上91市场搜索#super junior粉丝团#,或者直接到页面下载http://m.ixingji.com/m.html?p=X16,大家帮忙捧捧场
JSON 是現時流行的資料格式,與 XML 相比,JSON 更為輕巧。在傳輸相同資料時,JSON 在大部份情況也會較 XML 的檔案小,在手機網路上傳輸 JSON 亦會比 XML快。
在 iPhone Cocoa Touch Framework 中並沒有 Library 去操作 JSON 資料格式。幸好有一些人為 Objective C 製作了能夠操作 JSON資料格式的 Library。
{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]; NSString *jsonStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; SBJsonParser *parser = [[SBJsonParser alloc] init]; NSDictionary *json = [parser objectWithString:jsonStr error:nil]; NSDictionary *glossary = [json objectForKey:@"glossary"]; NSString *glossaryTitle = [glossary objectForKey:@"title"]; NSDictionary *glossDiv = [glossary objectForKey:@"GlossDiv"]; NSString *glossDivTitle = [glossDiv objectForKey:@"title"]; NSArray *glossSeeAlso = [[[[glossDiv objectForKey:@"GlossList"] objectForKey: @"GlossEntry"] objectForKey: @"GlossDef"] objectForKey: @"GlossSeeAlso"]; NSLog(@"Glossary Title: %@", glossaryTitle); NSLog(@"GlossDiv Title : %@", glossDivTitle); NSLog(@"GlossSeeAlso item 1: %@", [glossSeeAlso objectAtIndex:0]); NSLog(@"GlossSeeAlso item 2: %@", [glossSeeAlso objectAtIndex:1]);
{ "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } }
["GML", "XML"]
如你所見,這是一個 Array, 所以回傳的 Object 是一個 NSArray Object。
最後打印出來的內容會是以下這些:
2010-08-27 15:15:44.003 JSON[47655:207] Glossary Title: example glossary 2010-08-27 15:15:44.049 JSON[47655:207] GlossDiv Title : S 2010-08-27 15:15:44.050 JSON[47655:207] GlossSeeAlso item 1: GML 2010-08-27 15:15:44.050 JSON[47655:207] GlossSeeAlso item 2: XML如果 JSON 資料是經由網路去讀取,可以用以下方法:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://pro.ctlok.com/data.json"]]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];範例下載: JSON.zip