我尝试将多个对象作为数组发送到具有RestKit
的服务器。不幸的是,我无法这样做
遵循我非常简单的对象以及RestKit的映射:
@interface MyExampleObject : NSObject
@property NSString *key;
@property NSString *value;
@end
@interface MyArray : NSObject
@property NSArray *array;
@end
RKObjectMapping *mappingObject = [RKObjectMapping mappingForClass:[MyExampleObject class]];
[mappingObject addAttributeMappingsFromDictionary:@{
@"key" : @"key",
@"value" : @"value"
}];
RKObjectMapping *mappingArray = [RKObjectMapping mappingForClass:[MyArray class]];
[mappingArray addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"dummy" toKeyPath:@"array" mappingObject]];
如果我这样做,我会得到以下结果:
{
"dummy" : [
{
"key" : "MyKey1",
"value" : "MyValue1"
},
{
"key" : "MyKey2",
"value" : "MyValue2"
}
]
}
但我只想要没有“键”的数组。像这样:
[
{
"key" : "MyKey1",
"value" : "MyValue1"
},
{
"key" : "MyKey2",
"value" : "MyValue2"
}
]
我很明显将relationshipMappingFromKeyPath
更改为nil
。但这并没有奏效(得到setObjectForKey: key cannot be nil
错误。)
如何将多个MyExampleObjects
作为JSON数组发送到我的服务器,我该怎么做?
正如Wain建议我删除了我的" Top-Mapping"。在最终映射之后:
RKObjectMapping *mappingObject = [RKObjectMapping mappingForClass:[MyExampleObject class]];
[mappingObject addAttributeMappingsFromDictionary:@{
@"key" : @"key",
@"value" : @"value"
}];
当我将这些内容发布到我的服务器时,我就是这样做的:
NSArray *array = [NSArray arrayWithObjects:myExampleObject1, myExampleObject2, nil];
[[RKObjectManager sharedManager] postObject:array path:@"/myPath/" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
...
}
答案 0 :(得分:2)
只需删除MyArray
对象和关联的映射,然后直接将NSArray
MyExampleObject
传递给post方法。 RestKit将理解它是一组对象来映射和做正确的事情。