【问题标题】:Objective-C / JSON, Array of dictionaries, parsing array nested in dictionaryObjective-C / JSON,字典数组,解析嵌套在字典中的数组
【发布时间】:2012-06-20 18:34:29
【问题描述】:

我正在解析的 JSON 可以在此处找到“已编辑”。

我可以正确地从这个 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,我将无法继续。

谢谢!

【问题讨论】:

    标签: objective-c json parsing nsarray nested


    【解决方案1】:

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

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

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

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

    您可以查看的另一件事是您有时在 json 中传递的空值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多