2014-02-14 2 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에서 상속 사용자 정의 클래스를 만들 수 있습니다.

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]; 

헤더 파일은 :

배열로 list.json 파일의 내용을 읽을 수있는 코드는

#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 

마지막으로 스토리 보드에서이 클래스를 테이블 뷰 컨트롤러의 사용자 정의 클래스로 지정하십시오. 희망이 도움이됩니다.

+0

고맙습니다. – user3273254

+0

@ user3273254 걱정할 필요가 없습니다. –

관련 문제