是否可以让restkit中的映射相互依赖。我有以下 JSON 结构:
{
"IdList": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
],
“Persons”: [
{
"Id": 2,
"Name": “James”,
"Description": “Tall”,
"Items": [
{
"Id": 1051,
"Name": “Hat”,
"Description": "",
“Accesories”: []
}
]
}
]
}
我有 2 个响应描述符,以便深入到数组 IdList 和 Persons。
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[MappingProvider personsMapping] method:RKRequestMethodGET pathPattern:nil keyPath:@"Persons"statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self addResponseDescriptor:responseDescriptor];
RKResponseDescriptor *IdsResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[MappingProvider IdsMapping] method:RKRequestMethodGET pathPattern:nil keyPath:@"IdList" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self addResponseDescriptor:IdsResponseDescriptor];
我的映射代码:
+ (RKDynamicMapping *)IdsMapping {
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Ids" inManagedObjectStore:[[CoreDataManager sharedInstance] objectStore]];
mapping.discardsInvalidObjectsOnInsert = YES;
[mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"theId"]];
RKDynamicMapping *idsMapping = [RKDynamicMapping new];
[dynamicTableIdsMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if (!representation) {
return nil;
} else {
return mapping;
}
return nil;
}];
return dynamicTableIdsMapping;
}
+ (RKDynamicMapping *)personsMapping {
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Persons" inManagedObjectStore:[[CoreDataManager sharedInstance] objectStore]];
mapping.assignsNilForMissingRelationships = YES;
mapping.assignsDefaultValueForMissingAttributes = YES;
mapping.discardsInvalidObjectsOnInsert = YES;
[mapping addAttributeMappingsFromDictionary:@{
@"Id": @"remoteID",
@"Name": @"name"
}];
mapping.identificationAttributes = @[ @"remoteID" ];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"Items"
toKeyPath:@"products"
withMapping:[MappingProvider itemsMapping]]];
RKDynamicMapping * dynamicMenuMapping = [RKDynamicMapping new];
[dynamicMenuMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if (!representation) {
return nil;
} else {
NSArray *categoryArray = [representation valueForKey:@"Items"];
if (!categoryArray || !categoryArray.count) {
return nil;
} else {
return mapping;
}
}
return nil;
}];
return dynamicMenuMapping;
}
我如何设法先映射 Persons 数组,然后再映射 IdList?如果人员包含值,我只需要映射 idList 数组。我想这样做,因为当 Persons 中的数据存在时,用户只呈现一个新 View ,因此也存在 idList。因此,如果 persons 数组为空,则不必映射 IdList。
最佳答案
您需要使用带有零键路径的单个响应描述符。该响应描述符的映射将是一个动态映射,它检查内容并返回一个处理两个子部分的映射(因此您需要一个容器类)或 nil(放弃映射过程)。
关于ios - Restkit映射依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627332/