App要與服務(wù)器交互才能達(dá)到數(shù)據(jù)更新和獲取資源
那么:
服務(wù)器返回客戶端的數(shù)據(jù)铐伴,一般返回兩種格式:JSON格式疑故、XML格式 (文件下載除外)
什么是JSON
輕量級(jí)數(shù)據(jù)格式杠览,一般用于數(shù)據(jù)交互
JSON格式:key必須使用雙引號(hào)
{"type" : "super", "user_name" : "jack"};
{"user_names" : ["jack", "rose", "jim"]}
JSON數(shù)據(jù)(NSData) -> OC對(duì)象(Foundation Object)
- {} -> NSDictionary @{}
- [] -> NSArray @[]
- "jack" -> NSString @"jack"
- 15 -> NSNumber @10
- 12.5 -> NSNumber @10.5
- true -> NSNumber @1
- false -> NSNumber @0
- null -> NSNull
Paste_Image.png
JSON解析方案
iOS中有四種解析方案
前三種:
第三方框架:JSONKit、 SBJson纵势、TouchJson(最差)
SBJson簡(jiǎn)單用法
NSData *data = nil;
NSDictionary *dict = [data JSONValue];
// JSON字符串也可以使用此方法
NSDictionary *dict1 = [@"{\"height\": 2}" JSONValue];
第四種:
蘋果自帶:NSJSONSerialization(性能最好踱阿,iOS5.0出現(xiàn))
JSON數(shù)據(jù)(NSData) -> OC對(duì)象(Foundation Object)
// 利用NSJSONSerialization類
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
在解析JSON方法NSJSONReadingOptions參數(shù):
- NSJSONReadingOptions
- NSJSONReadingMutableContainers = (1UL << 0)
- 創(chuàng)建出來的數(shù)組和字典就是可變
- NSJSONReadingMutableLeaves = (1UL << 1)
- 數(shù)組或者字典里面的字符串是可變的
- NSJSONReadingAllowFragments
- 允許解析出來的對(duì)象不是字典或者數(shù)組,比如直接是字符串或者NSNumber
- KNilOptions
- 如果不在乎服務(wù)器返回的是可變的還是不可變的钦铁,直接傳入KNilOptions软舌,效率最高!返回的就是不可變的
- NSJSONReadingMutableContainers = (1UL << 0)
如何解析JSON:
- (void)parseJSON
// JSON格式化:
{
// 0.請(qǐng)求路徑
NSURL *url = [NSURL URLWithString:@"http://110.20.256.139:30693/login?username=jack&pwd=superman123"];
// 1.創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請(qǐng)求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
/*
NSJSONReadingMutableContainers
NSJSONReadingMutableLeaves
NSJSONReadingAllowFragments
*/
// 解析JSON
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// 打印解析出來的結(jié)果
NSLog(@"%@", dict[@"success"]);
NSLog(@"%@", dict[@"error"]);
// **** 也可以將服務(wù)器返回的字典寫成plist文件
[dict writeToFile:@"/Users/leichao/Desktop/video.plist" atomically:YES];
}];
}
OC對(duì)象(Foundation Object)-> JSON數(shù)據(jù)(NSData)
// 利用NSJSONSerialization類
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
// 將字典轉(zhuǎn)成字符串
// NSJSONWritingPrettyPrinted : 好看的印刷
NSData *date = [NSJSONSerialization dataWithJSONObject:@{@"name" : @"jack"} options:NSJSONWritingPrettyPrinted error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
格式化服務(wù)器返回的JSON數(shù)據(jù)
在線格式化:
http://tool.oschina.net/codeformat/json
將服務(wù)器返回的字典或者數(shù)組寫成plist文件
[dict writeToFile:@"/Users/leichao/Desktop/video.plist" atomically:YES];
什么是XML
暫時(shí)不寫了