RestKit映射多个类型数组

时间:2013-05-30 13:50:31

标签: restkit restkit-0.20

我有以下JSON:

{
    "stream": [{
        "catalog": {}
    }, {
        "catalog": {}
    }, {
        "user": {}
    }]
}

具有以下映射规则:

[RKResponseDescriptor responseDescriptorWithMapping:catalogMapping
                                        pathPattern:nil keyPath:@"stream.catalog"
                                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

[RKResponseDescriptor responseDescriptorWithMapping:userMapping
                                        pathPattern:nil keyPath:@"stream.user"
                                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

映射工作正常,直到流中有多种类型的对象。当流包含多个对象时,比如说user和catalog restkit失败了这个断言:

NSCAssert([representation isKindOfClass:[NSDictionary class]], @"Expected a dictionary representation");

有结构地图吗?

1 个答案:

答案 0 :(得分:3)

我很高兴要求更改API,所以我们搬到了

{
    "stream": [{
        "type": "catalog",
        "other": "fields"
    }, {
        "type": "catalog"
        "other": "fields"
    }, {
        "type": "user"
        "other": "fields"
    }]
}

现在我使用动态映射:

    RKDynamicMapping* dynamicMapping = [RKDynamicMapping new];
    [dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
        if ([[representation objectForKey:@"type"] isEqualToString:@"catalog"]) {
            return catalogMapping;
        } else if ([[representation objectForKey:@"type"] isEqualToString:@"user"]) {
            return userMapping;
        }
//       ...
    }];


    [manager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:dynamicMapping
                                                                           pathPattern:nil keyPath:@"stream"
                                                                           statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];