3

RestKit を使用して、動的にネストされた属性を持つ NSArray を JSON にマップするにはどうすればよいですか?

' ' と呼ぶクラスがあります。このクラスには、DataModel他のさまざまなプロパティと共に、プロパティ が含まれていNSString*ますDataModel_tag。また、 class もありますUploadObj。その唯一の目的は、 の配列をアップロードするための基礎を提供することですDataModel。そのため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