2014-02-12 59 views
0

确定这里是我的本地JSON文件products.json我放在资源文件夹下:如何打印文本字段本地JSON文件的数据

"Products": [ 
       { 
       "Name": "Samsung LCD", 
       "Price": "40000", 
       "Ratings": 4.5, 
       "Barcode":1 
       }, 
       { 
       "Name": "Sony Cybershot", 
       "Price": "35000", 
       "Ratings": 3.5, 
       "Barcode":2 
       }, 
       { 
       "Name": "LG Refrigerator", 
       "Price": "40000", 
       "Ratings": 4, 
       "Barcode":3 
       }, 
       { 
       "Name":"Toshiba Microwave" , 
       "Price": "Hdhd", 
       "Ratings": 4.5, 
       "barcode":4 
       } 
       ] 

我有我想要的文本字段打印第一个产品的数据,即点击一个按钮,即三星液晶显示器。

这里的代码:(它显示空输出)也我需要导入任何文件?

  • (IBAction为)enterCode:(ID)发送方{

    NSLog(@"HI"); 
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"products" ofType:@"json"] 
    
    NSError *error = nil; 
    
    NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error]; 
    
    id JSONObject = [NSJSONSerialization 
           JSONObjectWithData:JSONData 
           options:NSJSONReadingAllowFragments 
           error:&error]; 
    
    _out1.text = [NSString stringWithFormat: 
           @"%@ %@ %@ %@", 
           JSONObject[@"products"][0][@"Name"], 
           JSONObject[@"products"][0][@"Price"], 
           JSONObject[@"products"][0][@"Ratings"], 
           JSONObject[@"products"][0][@"Barcode"], 
           nil]; 
    

    }

回答

0

JSON解析字典使用区分sensetive字符串作为键。当您在代码中引用products时,您的json的主键为Products。使用JSONObject[@"Products"][0][@"Name"]而不是您的版本。

此外,请检查您的products.json文件是否包含在Xcode的应用程序目标中,否则它将不会被复制到应用程序的包中。