如何在Cocoa中浏览JSON文件?

时间:2011-05-23 22:38:56

标签: cocoa json nsdictionary

嘿gus我知道已经有类似的问题,但没有人专门回答我的问题。

基本上我使用一个小JSON文件作为数据库,如下所示:

{
"dataBase" : [
  {"version" : "0.1", "creator" : "unknown", "creationDate" : "2011-05-22 21:29:11 +0200"}],

"clients" : [
{"id" : "0", "name" : "customer1"},
{"id" : "1", "name" : "customer2", "projects" : [
    {"id" : "0", "name" : "project1", "timestamps" : [
        {"id" : "0", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"},
        {"id" : "1", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"},
        {"id" : "2", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"}
    ]},
    {"id" : "0", "name" : "project2", "timestamps" : [
        {"id" : "0", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"},
        {"id" : "1", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"},
        {"id" : "2", "start" : "2011-05-21 21:29:11 +0200", "stop" : "2011-05-22 21:29:11 +0200"}
    ]}             
  ]}
]}

我正在使用YAJL框架解析JSON,如下所示:

yajl = [json yajl_JSON];

yajl在标题中声明为NSDictionary

如果我要求:

NSLog(@"creator Name: %@" ,[[yajl objectForKey:@"dataBase"] valueForKey:@"creator"]);

我明白了:

2011-05-24 00:31:36.887 YAJLParser [1800:903]创作者姓名:(     “未知” )

由于我不知道如何处理这些括号,所以我输了,但这只是问题的一小部分。

我的问题是如何访问,比如说customer2 project2的所有时间戳? 我尝试了一些我找到的搜索论坛,但我找不到(我设置正确)对我有用的东西......

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

浏览格式定义here。您会发现[yajl objectForKey:@"dataBase"]包含单个项目数组,而第一个项目中包含密钥creator

[[[yajl objectForKey:@"dataBase"] objectAtIndex:0] valueForKey:@"creator"]应返回正确的值。同样,客户端部分的遍历将是

NSArray *clients = [yajl objectForKey:@"clients"];
for (id client in clients) {
    NSArray *projects = (NSArray *)[client objectForKey:@"projects"];
    for (id project in projects) {
        NSArray *timestamps = (NSArray *)[project objectForKey:@"timestamps"];
        for (id timestamp in timestamps) {
            ...
        }
    }
}

这是访问project2 timestamp2 -

id timestamp = [[[[yajl objectForKey:@"clients"] objectAtIndex:1] objectForKey:@"timestamps"] objectAtIndex:1];

NSLog(@"%@ %@",[timestamp valueForKey:@"start"], [timestamp valueForKey:@"stop"]);