ios - 将 JSON 字符串解析为三个数组 Objective C

标签 ios objective-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 字符串。我的 View 加载方法如下:

- (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字符串解析成三个可变数组吗?我得到的错误是:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSDictionaryM objectAtIndex:]:无法识别的选择器发送到实例 0x1d59db30”

最佳答案

如果您自己创建文本文件,我建议您创建一个有效的 json 对象(因为您的数据看起来应该是 json)以保持数据整洁。类似这样:

{"aps":[{"type":"Banking","badge":5},{"Type":"Fraud","badge":12}]}

然后您可以执行以下操作(此代码未经过测试,可能您需要对其进行一些修改)但我希望您能有所了解:)

NSError*    error       = nil;
NSDictionary*    dict = nil;
//serialising the jsonobject to a dictionary
dict  = [NSJSONSerialization JSONObjectWithData:fileContents
                                              options:kNilOptions
                                                error:&error];
bankingNotifications =  [[NSMutableArray alloc] init];
fraudNotifications =  [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];

if (dict) {
    NSArray *dataArray = [dict objectForKey:@"aps"];
    NSDictionary* siteData    = nil;
    NSEnumerator* resultsEnum   = [dataArray objectEnumerator];
    while (siteData = [resultsEnum nextObject])
    {
        //
        if( [[siteData objectForKey:@"Type"] isEqualToString: @"Banking"]) {
            [bankingNotifications addObject:notification];
            NSLog(@"Added object to banking array");
        } else if ([[siteData objectForKey:@"Type"] isEqualToString: @"Fraud"])
        {
            [fraudNotifications addObject:notification];
            NSLog(@"Added object to fraud array");
        }
        else if ([[siteData objectForKey:@"Type"] isEqualToString: @"Investment"])
        {
            [investmentNotifications addObject:notification];
            NSLog(@"Added object to investment array");
        }

    }
}

关于ios - 将 JSON 字符串解析为三个数组 Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15146785/

相关文章:

android - 使用 Xamarin Forms nuget Xam.Plugin.Media 用相机拍照

iphone - 寻找关于将 Pre-Storyboard 代码 (XCode4) 移动到 Storyboard 代码 (XCode5) 的教程

objective-c - 即使应用程序退出,如何在菜单栏中显示应用程序图标

javascript - 在 Angular 和 JSON 中填充正确的数据

asp.net-mvc - 将动态 JSON 对象传递给 Web API - Newtonsoft 示例

ios - 捆绑子目录访问

ios - Swift 4、Firebase 5.8.0 FCM token 无

iphone - 提醒应用程序 UI 是如何创建的?

objective-c - 如何在 SWIFT 中实现 Objective-C 回调处理程序?

java - 用于 Java 的 JWT(JSON Web token )库