问题
I'm trying to map some JSON data with RestKit, and have so far been unable to do it right. The data is a hierarchical set of days and registrations. It looks like the following (not a possibility for me to change it):
{
"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,
}
}
My code looks like the following:
- (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"];
}
It happily returns the days, but I am unable to find a good way to map the relationship between the two types,
Any push in the right direction would be greatly appreciated,
Best Regards, Tommy
回答1:
This worked for me:
- (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"];
}
This gives me a day object with a nice array of hour registrations as an NSArray. For reference, it looks like this:
@interface Day : NSObject
@property (nonatomic, readonly, copy) NSDate *date;
@property (nonatomic, readonly, strong) NSMutableArray *registrations;
@end
来源:https://stackoverflow.com/questions/13279533/restkit-problems-mapping-complex-nesting-multiple-levels-needing-forcecollecti