Objective-C / JSON,字典数组,解析嵌套在字典中的数组

时间:2012-06-20 18:34:29

标签: objective-c json parsing nsarray nested

我正在解析的JSON可以在这里找到'redacted'。

除了通知和设备之外,我可以正确地从这个JSON中获取所有对象。 能够获得包含'deviceId'的设备字典数组我遇到了很多麻烦。我的代码现在看起来像这样

dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL:
                    iViuListOfCustomersURL];

    [self performSelectorOnMainThread:@selector(fetchedData:)
                          withObject:data waitUntilDone:NO];
});




- (void) fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json;
    json = [NSJSONSerialization
                          JSONObjectWithData:responseData // 1

                          options:kNilOptions
                          error:&error]; 

    NSArray* customers = json; 


    for(int i = 0; i < customers.count ; i++){
        NSDictionary *customer = [customers objectAtIndex:i];
        cmsServer = [customer objectForKey:@"cmsServer"]; 
        iconUrl = [NSURL URLWithString:[customer objectForKey:@"iconUrl"]];
        wideLogo = [customer objectForKey:@"wideLogo"]; 
        customerNo = [NSNumber numberWithInt:[[customer objectForKey:@"customerNo"] intValue]];
        placeName = [customer objectForKey:@"placeName"];
        distance = [NSNumber numberWithFloat:[[customer objectForKey:@"distance"] floatValue]];
        placeId = [NSNumber numberWithInt:[[customer objectForKey:@"placeId"] intValue]];
        address = [customer objectForKey:@"address"];
        cmsName = [customer objectForKey:@"cmsName"]; 
        hasLocations = [NSNumber numberWithInt:[[customer objectForKey:@"hasLocations"]intValue]];
        isFavorite = [NSNumber numberWithInt:[[customer objectForKey:@"isFavorite"] intValue]];
        longitude = [NSNumber numberWithFloat:[[customer objectForKey:@"longitude"] floatValue]];
        latitude = [NSNumber numberWithFloat:[[customer objectForKey:@"latitude"] floatValue]];
        hasArtifacts = [NSNumber numberWithInt:[[customer objectForKey:@"hasArtifacts"]intValue]];

        // I have tried a number of things and this was what I had for the last try.
        devices = [NSArray arrayWithObject:[customer objectForKey:@"devices"]];
        NSLog(@"%@",devices.count);
    }

}

我对objective-c相对较新,想要自己解决这个问题,但我在这个问题上花了太多时间,如果没有这些设备ID,我就无法继续。

谢谢!

1 个答案:

答案 0 :(得分:1)

我不知道它是否会有所作为,但你试过了吗?

devices = [NSArray arrayWithArray:[customer objectForKey:@"devices"]];

您可以尝试的另一件事是浏览其中的元素并将它们逐个添加到设备中:

for(DeviceObject *deviceObject in [customer objectForKey:@"devices"])
{
  [devices addObject:deviceObject];
}

你可以研究的另一件事是你有时在json中传递的空值。