1
我想讀取我的Objective-C應用程序中的json文件,但不幸的是我得到一個RuntimeException。確切的錯誤是:嘗試閱讀Objective-C中的JSON文件
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
我的JSON文件被稱爲「Transactions.json
[{ "transaction": "300001", "date": "1/1/11", "type": "ABC", "status": "State1" },
{ "transaction": "300002", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300003", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300004", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300005", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300006", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300007", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300008", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300009", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300010", "date": "4/4/14", "type": "XYZ", "status": "State4" } ]
我的方法讀取文件看起來是這樣的:
int main(int argc, const char * argv[])
{
@autoreleasepool {
// Create the managed object context
NSManagedObjectContext *context = managedObjectContext();
// Custom code here...
// Save the managed object context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
exit(1);
}
NSError *err = nil;
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Transactions" ofType:@"json"];
NSLog(@"Hello: %@", dataPath);
NSArray *transaction = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];
NSLog(@"Transaction list: %@", transaction);
}
return 0;
}
我不什麼」不明白爲什麼當我讀取JSON文件時,NSData對象會變成空值?任何人都可以看到我在做什麼錯了嗎?只是爲了記錄,我試圖檢查JSON文件中的多餘空格,並且嘗試過placin g我的應用程序文件夾中的不同位置的JSON文件,並沒有任何工作。
在此先感謝所有回覆的人。
這是iOS還是OSx? 「dataPath」記錄的值是什麼? –
而且,一般來說:不要「連鎖」操作在一起。將NSData指針分配給一個臨時變量,然後使用該臨時變量來提供NSJSONSerialization。使調試更簡單。 –
並記錄「err」中的內容。 –