使用RestKit发布多个对象(作为JSON-Array)

时间:2014-10-20 13:54:09

标签: ios objective-c restkit restkit-0.20

我尝试将多个对象作为数组发送到具有RestKit的服务器。不幸的是,我无法这样做 遵循我非常简单的对象以及RestKit的映射:

示例对象

@interface MyExampleObject : NSObject

@property NSString *key;
@property NSString *value;

@end

包含多个MyExampleObject

的Array-Object
@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) {
...
}

1 个答案:

答案 0 :(得分:2)

只需删除MyArray对象和关联的映射,然后直接将NSArray MyExampleObject传递给post方法。 RestKit将理解它是一组对象来映射和做正确的事情。