3

我是 ios/RESTKIT 的新手。我正在尝试使用 RESTKIT 从 ios 设备使用 Web 服务。json 返回可能有 2 种可能的结果。

A)Failure上,json 结果如下所示(结果为字符串“null”。错误代码可用):

{
    status: false,
    result: null
    error: NO_SUCH_USER
}

(A) 的映射

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[WsReturn class]];
    [mapping mapKeyPath:@"result" toAttribute:@"result"];
    [mapping mapKeyPath:@"status" toAttribute:@"status"];
    [mapping mapKeyPath:@"error" toAttribute:@"error"];
    [objectManager.mappingProvider setMapping:mapping forKeyPath:@"/"];

B)Success上,它看起来像(结果是一个“复杂对象”。错误代码为空):

{
    status: true,
    result: {   
       name: "Some User",
       tasks: [
            {
              name: "Some Task1",
              taskId: 10
            },
            {
              name: "Some Task2",
              taskId: 20
            }
       ]
    },
    error: null
}

(B) 的映射

RKObjectMapping* taskMapping = [RKObjectMapping mappingForClass:[Task class]];
    [taskMapping mapKeyPath:@"name" toAttribute:@"name"];
    [taskMapping mapKeyPath:@"taskId" toAttribute:@"taskId"];
    [objectManager.mappingProvider setMapping:taskMapping forKeyPath:@"tasks"]; 

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[Result class]];
    [resultMapping mapKeyPath:@"name" toAttribute:@"name"];
    [resultMapping mapRelationship:@"tasks" withMapping:taskMapping];
    [objectManager.mappingProvider setMapping:resultMapping forKeyPath:@"result"];

RKObjectMapping* cmplxMapng = [RKObjectMapping mappingForClass:[WsReturn class]];
    [cmplxMapng mapKeyPath:@"status" toAttribute:@"status"];
    [cmplxMapng mapKeyPath:@"error" toAttribute:@"error"];
    [cmplxMapng mapRelationship:@"result" withMapping:resultMapping];
    [objectManager.mappingProvider setMapping:cmplxMapng forKeyPath:@"/"];

问题

1)(A)工作正常。(B) 没有。你能提供一些指点吗?

2) 对于同一个 web 服务调用,“结果”部分可以是字符串(null)或复杂对象。那么如何在代码中处理这个问题呢?我要通过哪个映射?映射或 cmplxMapng(更改名称以避免水平滚动)?

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/myUrl"
objectMapping: HOW_TO_DECIDE_WHICH_MAPPING_TO_PASS_HERE委托:self];

我相信这是一种常见的情况。我搜索了,但找不到相关的例子。也许我看错了地方。关于如何解决这个问题的想法/指针将有所帮助。谢谢。

4

1 回答 1

5

所以这就是我解决它的方法 -

1)我替换了这一行:

[objectManager.mappingProvider setMapping:taskMapping forKeyPath:@"tasks"];    

用这个:(注意forKeyPath)

[objectManager.mappingProvider setMapping:uooMapping forKeyPath:@"result.tasks"]; 

2)关注此线程http://groups.google.com/group/restkit/browse_thread/thread/89b25b3f0f7e0177并按照 Blake 的建议添加此行:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; 

调用 loadObjectsAtResourcePath之前

3)至于以不同方式映射对象,我发现传递 cmplxMapng 似乎总是有效。

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/myUrl"     
                                 objectMapping:cmplxMapng delegate:self];

因此,如果“结果”部分以字符串“null”的形式返回,我会得到“(null)”的结果和“状态”和“错误”字段的映射正确。作品!

希望这可以帮助某人。

于 2011-12-14T16:50:09.180 回答