好的,这是我放在资源文件夹下的本地json文件products.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
}
]
我有一个文本字段,我想打印第一个产品的数据,即单击按钮时的三星lcd。
这里是代码:(显示空输出)我还需要导入任何文件吗?
(IBAction)enterCode:(id)sender {
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 :(得分:0)
JSON解析字典使用区分大小写的字符串作为键。当您在代码中引用Products
时,您的json主键为products
。使用JSONObject[@"Products"][0][@"Name"]
代替您的版本。
另外,请检查您的products.json文件是否包含在Xcode中的应用程序目标中,否则它将不会被复制到应用程序包中。