RestKit:映射复杂嵌套的问题,需要forceCollectionMapping的多个级别

时间:2012-11-07 22:41:53

标签: objective-c ios mapping restkit

我正在尝试使用RestKit映射一些JSON数据,并且到目前为止还无法正确执行。 数据是一组分层的日期和注册。它看起来如下(我不可能改变它):

{
  "days": 
  {
    "2012-10-29": {
        "2106303": {
            "activityCode": "LU",
            "approved": false,
            "hours": 0.5,
            "description": "some description",
        },
        "2106304": {
            "activityCode": "VF",
            "approved": false,
            "hours": 7.5,
            "description": "some other description",
        }
        },
        "2012-10-30": null,
  }
}

我的代码如下所示:

- (void)setupWeekMappingForManager:(RKObjectManager *)manager
{
    RKObjectMapping *registrationMapping = [RKObjectMapping mappingForClass:[Registration class]];
    registrationMapping.forceCollectionMapping = YES;
    [registrationMapping mapKeyOfNestedDictionaryToAttribute:@"registrationNumber"];

    RKObjectMapping *dayMapping = [RKObjectMapping mappingForClass:[Day class]];
    dayMapping.forceCollectionMapping = YES;
    [dayMapping mapKeyOfNestedDictionaryToAttribute:@"date"];

    // how can this relationship be mapped?
    [dayMapping mapKeyPath:@"(date)." toRelationship:@"registrations" withMapping:registrationMapping]; 

    [manager.mappingProvider setMapping:dayMapping forKeyPath:@"days"];
}

它很高兴地回归日子,但我无法找到一种很好的方式来映射两种类型之间的关系,

非常感谢任何向正确方向的推动,

最诚挚的问候, 托米

1 个答案:

答案 0 :(得分:1)

这对我有用:

- (void)setupWeekMappingForManager:(RKObjectManager *)manager
{
    RKObjectMapping *registrationMapping = [RKObjectMapping mappingForClass:[Registration class]];
    registrationMapping.forceCollectionMapping = YES;
    [registrationMapping mapKeyOfNestedDictionaryToAttribute:@"registrationNumber"];
    [registrationMapping mapKeyPath:@"(registrationNumber).description" toAttribute:@"description"];

    RKObjectMapping *dayMapping = [RKObjectMapping mappingForClass:[Day class]];
    dayMapping.forceCollectionMapping = YES;
    [dayMapping mapKeyOfNestedDictionaryToAttribute:@"date"];
    [dayMapping mapKeyPath:@"(date)" toRelationship:@"registrations" withMapping:registrationMapping];

    [manager.mappingProvider setMapping:dayMapping forKeyPath:@"days"];
}

这给了我一个日期对象,它有一个很好的小时注册数组作为NSArray。 作为参考,它看起来像这样:

@interface Day : NSObject
@property (nonatomic, readonly, copy) NSDate *date;
@property (nonatomic, readonly, strong) NSMutableArray *registrations;
@end