SBJSON失去了引用马克斯

时间:2011-05-02 23:10:35

标签: iphone objective-c json

我正在使用SBJSON解析器来解析JSON响应:

{"status":0,"sessions":[{"name":"kldlksdklsdkl","active":false,"status":"saved","type":"web","key":"30228ee71f09b93aaa2d1738","contributor_id":"lance","created_at":"Mon May 02, 2011 02:35 PM","closed_at":"Mon May 02, 2011 02:46 PM"}{"name":"Blahieririe","active":false,"status":"saved","type":"web","key":"dbd2bbcc8681bba6a6532051","contributor_id":"lance","created_at":"Mon May 02, 2011 01:42 PM","closed_at":"Mon May 02, 2011 02:34 PM"},{"name":"Jim","active":false,"status":"saved","type":"web","key":"ec5bcf18356a29bb4490841f","contributor_id":"lance","created_at":"Fri April 29, 2011 02:37 PM","closed_at":"Fri April 29, 2011 02:38 PM"}]}

来自使用此代码的服务器:

NSArray *sessionsArray = [dictionary objectForKey:@"sessions"];
    NSArray *tempArray = [[NSArray alloc] init];
    for(NSString *item in sessionsArray){
        NSLog(@"Session Found: \'%@\'",item);

        NSDictionary *myDictionary = [item JSONValue];
    }

我从我的JSON获得了一个很好的数组,但是当我尝试将每个部分放入一个NSDictionary时,它给了我一个例外,我对它进行了NSLoged并发现引号已从某些键和/或中移除价值如下所示:

{
active = 1;
"contributor_id" = lance;
"created_at" = "Mon May 02, 2011 03:26 PM";
key = e10e5feeea3425ae213cb4cc;
name = "JSON TEST";
status = active;
type = web;
}

它是JSON解析器中的错误吗?或者我在做一些愚蠢的事情?

1 个答案:

答案 0 :(得分:4)

引号未被“删除”。

在JSON中,引用了每个字符串,但引号本身不是字符串的一部分。例如,如果你写

NSArray *sessionsArray = [dictionary objectForKey:@"sessions"];
NSDictionary *session = [sessionArray objectAtIndex:0];
NSString sessionName = [session objectForKey:@"name"];

相应的会话名称不会显示引号。

当你NSLog()字典或数组时,Cocoa使用NeXTSTEP属性列表格式来表示字典/数组。在这种格式中,如果值是简单的单词,则引号是可选的。

也就是说,您应该按如下方式枚举这些JSON数据:

NSString *jsonString = …;
NSDictionary *jsonResult = [jsonString JSONValue];
NSArray *sessionsArray = [jsonResult objectForKey:@"sessions"];
for (NSDictionary *session in sessionArray) {
    NSString *sessionName = [session objectForKey:@"name"];
    BOOL sessionActive = [[session objectForKey:@"active"] boolValue];
    NSString *sessionStatus = [session objectForKey:@"status"];
    …
}