2014-02-14 59 views
5

我有我自己的json文件「list.json」以獲取如下示例信息的列表。我的JSON文件是位於Xcode內部的 ,我想向表格顯示我的信息,請給我一些提示和幫助以實現此操作,我該如何解析本地json並在表中加載信息。在UITableView中加載本地json信息

[ 
{ 
    "number": "1", 
    "name": "jon" 
}, 
{ 
    "number": "2", 
    "name": "Anton" 
}, 
{ 
    "number": "9", 
    "name": "Lili" 
}, 
{ 
    "number": "7", 
    "name": "Kyle" 
}, 
{ 
    "display_number": "8", 
    "name": "Linda" 
} 
] 

回答

12

您可以創建一個從的UITableViewController繼承的自定義類。

讀取list.json文件的內容到一個數組中的代碼是:

NSString * filePath =[[NSBundle mainBundle] pathForResource:@"list" ofType:@"json"]; 

    NSError * error; 
    NSString* fileContents =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; 


    if(error) 
    { 
     NSLog(@"Error reading file: %@",error.localizedDescription); 
    } 


    self.dataList = (NSArray *)[NSJSONSerialization 
           JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] 
           options:0 error:NULL]; 

和標題文件是:

#import <UIKit/UIKit.h> 

@interface TVNA_ReadingDataTVCViewController : UITableViewController 

@end 

的實現是:

#import "TVNA_ReadingDataTVCViewController.h" 

@interface TVNA_ReadingDataTVCViewController() 

@property NSArray* dataList; 

@end 

@implementation TVNA_ReadingDataTVCViewController 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self readDataFromFile]; 

    [self.tableView reloadData]; 
} 


-(void)readDataFromFile 
{ 
    NSString * filePath =[[NSBundle mainBundle] pathForResource:@"list" ofType:@"json"]; 

    NSError * error; 
    NSString* fileContents =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; 


    if(error) 
    { 
     NSLog(@"Error reading file: %@",error.localizedDescription); 
    } 


    self.dataList = (NSArray *)[NSJSONSerialization 
           JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] 
           options:0 error:NULL]; 
} 



#pragma mark - Table view data source 

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

    return 1; 
} 

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

    return self.dataList.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    id keyValuePair =self.dataList[indexPath.row]; 

    cell.textLabel.text = keyValuePair[@"name"]; 

    cell.detailTextLabel.text=[NSString stringWithFormat:@"ID: %@", keyValuePair[@"number"]]; 
    return cell; 
} 


@end 

最後,在您的故事板上,將此類指定爲Table View Controller的自定義類。希望這可以幫助。

+0

非常感謝你 – user3273254

+0

@ user3273254不用擔心 –