這篇文章主要是:
1.原生加載Json
2.解析Json
3.重寫description方法
1.加載json
//從web服務器直接加載數(shù)據(jù)
NSString *str = @"http://localhost/02/";
//提示NSData本身具有同步方法 但在開發(fā)中不要使用
//在使用nsdata方法時蚁堤,無法制定超時時間际看, 如果服務器不正常 會影響用戶體驗
//NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
//1.建立NSURL
NSURL *url = [NSURL URLWithString:str];
//2.建立NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
//3.利用nsurlconnection同步方法加載數(shù)據(jù)
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//錯誤處理
if(data != nil){
//result僅用跟蹤調(diào)試使用
// NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//json數(shù)據(jù)處理
[self handlerJsonData:data];
}else if (data == nil && error != nil){
NSLog(@"空數(shù)據(jù)");
}else{
NSLog(@"%@",error.localizedDescription);
}
2.處理json數(shù)據(jù)([self handlerJsonData:data];)
//json文件中的[]表示的是一個數(shù)組
//1.反序列化json數(shù)據(jù)
/*
序列化: 將NSObject轉(zhuǎn)換成序列數(shù)據(jù)渡讼,以便可以通過互聯(lián)網(wǎng)進行傳輸
反序列化: 將網(wǎng)絡上獲取的數(shù)據(jù) 反向生成為對象
*/
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//提示 如果開發(fā)網(wǎng)絡應用赏殃,可以講反序列化出來的對象须肆,保存至沙箱 以便后續(xù)開發(fā)使用
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0] stringByAppendingPathComponent:@"json.plist"];
NSLog(@"%@",path);
[array writeToFile:path atomically:YES];
//給列表賦值
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);
注意:返回的json數(shù)據(jù)中最外邊是[{},{},{},---- ],這樣序列化之后是數(shù)組
{{}煎源,{}稳衬,{}-----}這樣的序列化之后是字典
**json數(shù)據(jù)保存到沙箱**
//提示 如果開發(fā)網(wǎng)絡應用羹铅,可以講反序列化出來的對象蚀狰,保存至沙箱 以便后續(xù)開發(fā)使用
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0] stringByAppendingPathComponent:@"json.plist"];
NSLog(@"%@",path);
[array writeToFile:path atomically:YES];
3.重寫類的description方法
重寫description方法可以顯示類的詳細信息
- (NSString *)description
{
return [NSString stringWithFormat:@"<Video: %p,videoId:%ld,name %@"
" ,length:%ld ,videourl :%@,imagURl:%@,desc:%@,"
"teacher:%@>",self,(long)self.videoId,self.name,self.length,self.videoURL,self.imageURL,self.desc,self.teacher];
}
一起學習,一起進步职员,講不出再見.........很好聽麻蹋!