我正嘗試使用從目標文本c中讀取的數據。我從文本文件中讀取的數據是:將JSON字符串解析爲三個數組Objective C
{"aps":{"alert":"Test 1!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 2!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 3!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 4!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 5!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}
讀取一次,我將文件分割成一個陣列的分隔符「|」。然後,我想進一步將其分爲3個不同的陣列:基於「類型」關鍵字的銀行業務,欺詐和投資。但是,我似乎無法達到解析JSON字符串,一旦我把它分成數組。我的觀點沒有負荷的方法如下:
- (void)viewDidLoad {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/AccountNotifications.txt", documentsDirectory];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil];
NSArray *fileData = [fileContents componentsSeparatedByString:@"|"];
if (fileContents != NULL)
{
bankingNotifications = [[NSMutableArray alloc] init];
fraudNotifications = [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];
for (i = 0; i < [fileData count]; i++)
{
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:@"aps"];
if ([[[items objectAtIndex:i] objectForKey:@"Type"] isEqual: @"Banking"])
{
[bankingNotifications addObject:fileData[i]];
NSLog(@"Added object to banking array");
}
if ([[[items objectAtIndex:i] objectForKey:@"Type"] isEqual: @"Fraud"])
{
[fraudNotifications addObject:fileData[i]];
NSLog(@"Added object to fraud array");
}
if ([[[items objectAtIndex:i] objectForKey:@"Type"] isEqual: @"Investment"])
{
[investmentNotifications addObject:fileData[i]];
NSLog(@"Added object to investment array");
}
} }
有這三個行錯誤:
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:@"aps"];
能否請你幫我解析JSON字符串成三個可變數組?我得到的錯誤是:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM objectAtIndex:]: unrecognized selector sent to instance 0x1d59db30'
'' - [__ NSDictionaryM objectAtIndex:]:無法識別的選擇器發送到實例'意味着你正在嘗試像字典一樣處理字典。 (仔細閱讀消息,你可以看到。)你分離的字符串代表JSON「對象」(字典),而不是數組(而下一層也是「對象」),所以這可能是你的問題。 (和YY是分開的字符串,只是將它們放入一個包含JSON數組中?) – 2013-02-28 22:29:15
這是你開始出錯的地方:'NSArray * items = [json valueForKeyPath:@「aps」];'。該操作的結果是NSDictionary,而不是NSArray。 – 2013-02-28 22:31:49
不應該只是將3個數組放在文件中而不是使用'|'?這將使它成爲一個合格的JSON文件。 – nielsbot 2013-02-28 22:47:44