3

如何使用 RestKit 将 NSArray 映射到具有动态嵌套属性的 JSON?

我有一个名为“ DataModel”的类,它与其他各种属性一起包含NSString*属性DataModel_tag。我还有一个 class UploadObj,其唯一目的是为上传DataModels 数组提供基础。因此,UploadObj包含一个属性:

@property NSMutableArray* DataModels;

这需要以以下格式映射到 JSON:

{
    "DataModels" : 
    {
        "DataModel tag 1" : 
            {
                // other properties of DataModel instance 1 here
            },
        "tag for DataModel 2" : 
            {
                // other properties of DataModel instance 2 here
            }
    }
}

我目前正在尝试遵循 RestKit 对象映射文档,并提出了以下方法:

+(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]];   
}

当我尝试映射此对象时,我会收到每个 DataModel 属性的以下输出:

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...

如何正确映射此对象?

谢谢!

4

0 回答 0