具有多个根对象的 Restkit 对象映射

Posted

技术标签:

【中文标题】具有多个根对象的 Restkit 对象映射【英文标题】:Restkit object mapping with multiple root objects 【发布时间】:2012-08-14 07:03:00 【问题描述】:

我有一个 Web 服务,它返回以下格式的 JSON:


"client": 
         "firstName": "Aaron"
         ,
"error": 
         "code":""
         

我正在 restkit 中设置映射。我不断收到以下错误:

Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "Could not find an object mapping for keyPath: ''" UserInfo=0x5961f0 =RKObjectMapperKeyPath, NSLocalizedDescription=Could not find an object mapping for keyPath: ''

这是我设置映射的方式:

    [[RKObjectManager sharedManager].mappingProvider setMapping:[Client objectMapping] forKeyPath:@"client"];
    [[RKObjectManager sharedManager].mappingProvider setMapping:[ErrorObject objectMapping] forKeyPath:@"error"];

客户端映射:

+(RKObjectMapping*) objectMapping 
   RKObjectMapping* responseObjectMapping = [RKObjectMapping mappingForClass:[Client class]];
   [responseObjectMapping setRootKeyPath:@"client"];
   [responseObjectMapping mapKeyPathsToAttributes:
    @"firstName", @"firstName",
    nil];
   return responseObjectMapping;

错误映射:

+(RKObjectMapping*) objectMapping 
   RKObjectMapping* responseObjectMapping = [RKObjectMapping mappingForClass:[ErrorObject class]];
   [responseObjectMapping setRootKeyPath:@"error"];
   [responseObjectMapping mapKeyPathsToAttributes:
    @"code", @"code",
    nil];
   return responseObjectMapping;

并像这样调用服务:

//Send initial load request
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/getdetails" stringByAppendingQueryParameters:params] usingBlock:^(RKObjectLoader *loader) 
    loader.delegate = self;
    loader.userData = INITIAL_LOAD_REQUEST;
];

编辑:

我通过以下建议解决了我的问题,并将我的映射从 init 方法移动到对象加载器块中,如下所示:

    //Send initial load request
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/getdetails" stringByAppendingQueryParameters:params] usingBlock:^(RKObjectLoader *loader) 
    loader.delegate = self;

    //set mapping explicitly
    RKObjectMappingProvider *provider = [[RKObjectMappingProvider alloc] init];
    [provider setMapping:[Clien objectMapping] forKeyPath:@"client"];
    [provider setMapping:[ErrorObject objectMapping] forKeyPath:@"error"];
    [loader setMappingProvider:provider];

    loader.userData = INITIAL_LOAD_REQUEST;
];

【问题讨论】:

【参考方案1】:

删除线

[responseObjectMapping setRootKeyPath:@"client"];

[responseObjectMapping setRootKeyPath:@"error"];

【讨论】:

给我同样的错误:Request didFailLoadWithError: Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "Could not find an object mapping for keyPath: ''" UserInfo=0x5a56e0 =RKObjectMapperKeyPath, NSLocalizedDescription=Could not find an object mapping for keyPath: '' 修复了它,您的评论引导我走上正确的道路,我将我的映射从 init 方法移动到为加载程序显式设置它们。编辑我的问题以显示这一点。谢谢。

以上是关于具有多个根对象的 Restkit 对象映射的主要内容,如果未能解决你的问题,请参考以下文章

RestKit 对象映射与外键和服务

如何使用 RestKit 映射根词典?

Restkit 映射问题 - 将新创建的托管对象发布到服务器

RestKit 0.20 嵌套对象映射(对象树的路径不同)

RestKit:将嵌套数组映射到对象

RestKit 相同对象上的一对一映射,除了