RestKit 0.20 - 动态嵌套对象映射

时间:2013-02-17 18:03:11

标签: objective-c json mapping restkit

我正在使用Objective C项目,它使用RestKit框架来解析JSON响应。 现在我需要一些关于以下情况的对象映射设置的帮助: JSON响应:

    {
   "data": {
       "SOME.API.Auth": {
           "maxVersion": 2,
           "minVersion": 1,
           "path": "auth.cgi"
       },
       "SOME.Station": {
           "maxVersion": 1,
           "minVersion": 1,
           "path": "Station/task.cgi"
       }
   },
   "success": true
}

以及以下对象:

@interface Response : NSObject
@property (strong, nonatomic) NSArray *data;
@property (assign, nonatomic) BOOL success;
@end


@interface SomeAPIInfo : NSObject
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *path;
@property (strong, nonatomic) NSString *minVersion;
@property (strong, nonatomic) NSString *maxVersion;
@end

这是我的映射设置:

RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[Response class]];
[responseMapping addAttributeMappingsFromDictionary:@{@"success": @"success"}];

RKObjectMapping *dataObjectMapping =  [RKObjectMapping mappingForClass:[SomeAPIInfo class]];
dataObjectMapping.forceCollectionMapping = YES;
[dataObjectMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"name"];
[dataObjectMapping addAttributeMappingsFromDictionary:@{
@"(name).path": @"path",
@"(name).minVersion": @"minVersion",
@"(name).maxVersion": @"maxVersion"}];


[responseMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"data"
                                                                               toKeyPath:@"data"
                                                                             withMapping:dataObjectMapping]];

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
                                                                                  pathPattern:nil
                                                                                      keyPath:nil
                                                                                  statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];


[_objectManager addResponseDescriptor:responseDescriptor];

问题是“数据”对象未正确映射: NSArray *数据; 填充了2个“SomeAPIInfo”对象。 name已正确填充,但其他值(path,maxVersion,minVersion)为空。

我做错了什么? 是否有另一种方法来映射“数据”对象?也许直接进入NSDictionary,所以“Some.API.Auth”将是关键,“SomeAPIInfo”将是对象(没有“name”属性)。

感谢您的帮助!

编辑:我认为由于键中的点(“SOME.API.Auth”),映射无效。

RKMappingOperation.m:
- (NSArray *)simpleAttributeMappings
{
    NSMutableArray *mappings = [NSMutableArray array];
    for (RKAttributeMapping *mapping in self.nestedAttributeMappings) {
        if ([mapping.sourceKeyPath rangeOfString:@"."].location == NSNotFound) {
            [mappings addObject:mapping];
        }
    }

1 个答案:

答案 0 :(得分:0)

我遇到了由RestKit https://github.com/RestKit/RestKit/issues/1532中的错误引起的类似问题。我试图通过创建具有相同结构但没有点的假JSON响应消除可能的点问题,并查看问题是否仍然存在。