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