NSJSON如何解析

时间:2012-08-29 16:56:20

标签: ios json ios5 viewdidload nsjsonserialization

我遇到了通过特定的“”获取json格式的问题。我可以看到它是一本字典,所以我把字典变成一个错误的数组吗?我试图拉出“isReserevble = true”的记录,然后根据UIDatepicker中的用户选择,在表格视图单元格中显示“begin”。 json正在使用NSlog,但我无法解决这个问题。感谢

看起来我有一系列词典。我还会使用相同的方法吗?

这是我的代码。

- (void)viewDidLoad
{
    [super viewDidLoad];
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: 
                        kLatestKivaLoansURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) 
                               withObject:data waitUntilDone:YES];

    });

}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data

NSError* error;

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

NSArray* myslots =[json objectForKey:@"slots"];
NSLog(@"allslots: %@", myslots);


  NSMutableArray *datesArray = [[NSMutableArray alloc] init];
for (NSDictionary *slots in json){
    NSLog(@"isReservable = %@",[myslots objectForKey:@"isReservable"]);
    if ([[myslots objectForKey:@"isReservable"]isEqualToString:@"1"]) 
    {
        NSLog(@"begin = %@",[myslots objectForKey:@"begin"]);
        [datesArray addObject:[myslots objectForKey:@"begin"]];
        NSLog(@"slots array count = %d",[datesArray count]);
    }

}
NSLog(@"This is the begin: %@", datesArray);

}

这是NSLog所有插槽的结果:

2012-08-29 11:54:26.531 GBSB[1137:15b03] allslots: {
    "2012-08-29 00:00:00 America/Los_Angeles" =     (
                {
            begin = "2012-08-29 00:00:00 America/Los_Angeles";
            end = "2012-08-29 08:00:00 America/Los_Angeles";
            isPending = 0;
            isReservable = 0;
            isReserved = 0;
            label = " ";
            span = 1;
        },
                {
            begin = "2012-08-29 08:00:00 America/Los_Angeles";
            end = "2012-08-29 08:15:00 America/Los_Angeles";
            isPending = 0;
            isReservable = 1;
            isReserved = 0;
            label = " ";
            span = 1;
        }
    );
}

好的:现在是我得到的

2012-08-30 09:28:30.812 GBSB[835:15b03] its a dictionary
2012-08-30 09:28:30.812 GBSB[835:15b03] isReservable = (null)
2012-08-30 09:28:30.812 GBSB[835:15b03] isReservable = (null)
2012-08-30 09:28:30.812 GBSB[835:15b03] isReservable = (null)
2012-08-30 09:28:30.813 GBSB[835:15b03] This is the begin: (
)

2 个答案:

答案 0 :(得分:1)

错误信息 - 再次 - 有帮助。试着解释一下:

-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x81e1c80

这意味着,您将objectForKey:消息发送到JSON 字符串对象而不是解析的NSDictionary 对象,这就是错误的。

答案 1 :(得分:0)

这就是导致你出现问题的一点:

for (NSDictionary *tempDict in self.json) {
    [datesArray addObject:[tempDict objectForKey:@"slots"]];
}

您认为您要求的是JSON的"slots"属性,但您不是,要求每个子词典"slots"属性你的JSON。

试试这个:

[datesArray addObject:[self.json objectForKey:@"slots"]];