1

我有以下 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)]];

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

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

有没有办法映射该结构?

4

1 回答 1

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)]];
于 2013-05-31T09:16:29.003 回答