Using RestKit to map an NSArray into JSON with dynamic nested attributes?
How can I use RestKit to map an NSArray into JSON with dynamic nested attributes?
I have a class which I'll call ' DataModel
', which, along with various other properties, contains the NSString*
property DataModel_tag
. I also have a class UploadObj
, the sole purpose of which is to provide a basis for uploading an array of DataModel
s. As such, UploadObj
contains a single property:
@property NSMutableArray* DataModels;
This needs to be mapped to JSON in the following format:
{
"DataModels" :
{
"DataModel tag 1" :
{
// other properties of DataModel instance 1 here
},
"tag for DataModel 2" :
{
// other properties of DataModel instance 2 here
}
}
}
I'm currently attempting to follow the RestKit object mapping documentation, and have come up with the following methods:
+(RKObjectMapping*)mappingForDataModel {
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:
[DataModel class]];
[mapping mapKeyOfNestedDictionaryToAttribute:@"DataModel_tag"];
mapping.forceCollectionMapping = YES;
mapping.rootKeyPath = @"DataModel_tag";
NSArray* propertyNames = // all properties, names obtained by introspection
for (NSInteger i = 0; i < [propertyNames count]; i++) {
NSString* propertyName = [propertyNames objectAtIndex:i];
if (![propertyName isEqualToString:@"DataModel_tag"]) {
// map (DataModel_tag).propertyName to propertyName
[mapping mapKeyPath:[NSString stringWithFormat:
@"(DataModel_tag).%@", propertyName]
toAttribute:propertyName];
}
}
return mapping;
}
+(void)configureMappingProviderForUpload {
RKObjectMapping* uploadMapping = [Utilities
simpleMappingForObject:[UploadObj class]
withFieldsOrNil:nil];
// ^ method not shown, but it just maps non-array properties to the object
// with the same name. This method works in other parts of the code.
[[RKObjectManager sharedManager] setSerializationMIMEType:RKMIMETypeJSON];
[[[RKObjectManager sharedManager] router]
routeClass:[UploadObj class]
toResourcePath:@"/test.php"];
RKObjectMapping *dataModelMapping = [Utilities mappingForDataModel];
[uploadMapping mapKeyPath:@"DataModels"
toRelationship:@"DataModels"
withMapping:dataModelMapping];
[[[RKObjectManager sharedManager] mappingProvider]
setSerializationMapping:[dataModelMapping inverseMapping]
forClass:[DataModel class]];
[[[RKObjectManager sharedManager] mappingProvider]
setSerializationMapping:[uploadMapping inverseMapping]
forClass:[UploadObj class]];
}
When I attempt to map this object, I receive this output for every DataModel attribute:
Destination object {
"<RK_NESTING_ATTRIBUTE>" = [DataModel_tag value for current instance]
} rejected attribute value [attribute value for current attribute on
current instance] for keyPath (DataModel_tag).[current attribute name].
Skipping...
How can I map this object correctly?
Thanks!
链接地址: http://www.djcxy.com/p/49196.html上一篇: RestKit映射没有键路径的字符串数组