我正在尝试使用从目标 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'