1

JSON array从我的服务器收到具有以下格式的:

{ messageArray: 
   [ { msgFrom: 'V351315826',
       msgDate: Tue Oct 29 2013 04:00:35 GMT+0000 (UTC),
       msgBody: 'Hi?',
       channelID: 'V351315826' },
     { msgFrom: 'V351315826',
       msgDate: Tue Oct 29 2013 04:00:38 GMT+0000 (UTC),
       msgBody: 'Hello!',
       channelID: 'V351315826' } ] }

我怎样才能循环通过它?

到目前为止得到的是:

NSError* error;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [(NSString *) message dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers
                                  error: &error];
NSArray *messageArray = [JSON objectForKey:@"messageArray"];

// Parse and loop through the JSON
for (NSDictionary * dataDict in messageArray) {
    NSString * messageID = [dataDict objectForKey:@"id"];
    NSString * msgFrom = [dataDict objectForKey:@"msgFrom"];
    NSString * msgTime = [dataDict objectForKey:@"msgDate"];

    NSLog(@"FROM ---> %@", dataDict);

}
4

1 回答 1

5

使用带有错误指针的方法时,最好在非 ARC 代码(ARC 中的冗余)中设置为并检查返回值NSError并检查返回的:nilnilNSError

NSError* error = nil;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [(NSString *) message dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers
                                  error: &error];

if (!JSON)
{
    NSLog(@"%@", [error localizedDescription]);
}
else
{
    NSArray *messageArray = [JSON objectForKey:@"messageArray"];

    // Parse and loop through the JSON
    for (NSDictionary * dataDict in messageArray) {
        NSString * messageID = [dataDict objectForKey:@"id"];
        NSString * msgFrom = [dataDict objectForKey:@"msgFrom"];
        NSString * msgTime = [dataDict objectForKey:@"msgDate"];

        NSLog(@"FROM ---> %@", dataDict);
    }
}

使用提供的 JSON 运行它会将其打印到控制台:

2013-10-28 22:28:20.552 SO question[12141:907] The operation couldn’t be completed. (Cocoa error 3840.)

似乎NSJSONSerialization很难解析这个。我自己对 JSON 不太熟悉。让我们看看当我们通过JSON 验证器运行 JSON 时会发生什么(将 JSON 粘贴到http://jsonlint.com,这是网络上的众多验证器之一)。这样做会产生几个语法错误。似乎键必须用双引号括起来,字符串也必须用双引号括起来。我假设这两个字典中的所有值都是字符串。清理语法后,JSON 如下所示:

{
    "messageArray": [
        {
            "msgFrom": "V351315826",
            "msgDate": "TueOct29201304: 00: 35GMT+0000(UTC)",
            "msgBody": "Hi?",
            "channelID": "V351315826"
        },
        {
            "msgFrom": "V351315826",
            "msgDate": "TueOct29201304: 00: 38GMT+0000(UTC)",
            "msgBody": "Hello!",
            "channelID": "V351315826"
        }
    ]
}

当我通过您的代码运行它时,它会打印出以下内容:

2013-10-28 22:36:02.018 SO question[12188:907] FROM ---> {
    channelID = V351315826;
    msgBody = "Hi?";
    msgDate = "TueOct29201304: 00: 35GMT+0000(UTC)";
    msgFrom = V351315826;
}
2013-10-28 22:36:02.018 SO question[12188:907] FROM ---> {
    channelID = V351315826;
    msgBody = "Hello!";
    msgDate = "TueOct29201304: 00: 38GMT+0000(UTC)";
    msgFrom = V351315826;
}

希望这会有所帮助!

于 2013-10-29T03:38:21.630 回答