如何使用 Restkit 来 POST JSON 并映射响应

发布于 2025-01-03 19:33:17 字数 2250 浏览 1 评论 0原文

我是第一次使用 RestKit,它的功能集看起来很棒。我已经多次阅读该文档,并且正在努力寻找一种将 JSON 参数 POST 到 feed 并映射 JSON 响应的方法。通过在 stackoverflow 上搜索,我找到了一种通过 GET 发送 JSON 参数的方法,但我的服务器只接受 POST。

这是我到目前为止的代码:

RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[CDIssue class]];
[objectMapping mapKeyPath:@"issue_id" toAttribute:@"issueId"];
[objectMapping mapKeyPath:@"title" toAttribute:@"issueTitle"];
[objectMapping mapKeyPath:@"description" toAttribute:@"issueDescription"];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"];
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"News.sqlite"];
objectManager.objectStore = objectStore;

NSDictionary params = [NSDictionary dictionaryWithObjectsAndKeys: @"myUsername", @"username", @"myPassword", @"password", nil];
NSURL *someURL = [objectManager.client URLForResourcePath:@"/feed/getIssues.json" queryParams:params];

[manager loadObjectsAtResourcePath:[someURL absoluteString] objectMapping:objectMapping delegate:self]

从另一个 stackoverflow 线程(http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using-restkit),我知道如何做一个简单的 POST使用以下代码请求:

RKClient *myClient = [RKClient sharedClient];
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

//User and password params
[params setObject:password forKey:@"password"];
[params setObject:username forKey:@"email"];

//The server ask me for this format, so I set it here:
[rpcData setObject:@"2.0" forKey:@"jsonrpc"];
[rpcData setObject:@"authenticate" forKey:@"method"];
[rpcData setObject:@"" forKey:@"id"];
[rpcData setObject:params forKey:@"params"];

//Parsing rpcData to JSON! 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:rpcData error:&error];    

//If no error we send the post, voila!
if (!error){
    [[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send];
}

我希望有人能帮助我将这两个代码片段结合成一个可行的解决方案。

I'm using RestKit for the first time, and its feature-set looks great. I've read the document multiple times now and I'm struggling to find a way to POST JSON params to a feed and map the JSON response. From searching on stackoverflow I found a way to send the JSON params via a GET, but my server only takes POST.

Here is the code I have so far:

RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[CDIssue class]];
[objectMapping mapKeyPath:@"issue_id" toAttribute:@"issueId"];
[objectMapping mapKeyPath:@"title" toAttribute:@"issueTitle"];
[objectMapping mapKeyPath:@"description" toAttribute:@"issueDescription"];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"];
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"News.sqlite"];
objectManager.objectStore = objectStore;

NSDictionary params = [NSDictionary dictionaryWithObjectsAndKeys: @"myUsername", @"username", @"myPassword", @"password", nil];
NSURL *someURL = [objectManager.client URLForResourcePath:@"/feed/getIssues.json" queryParams:params];

[manager loadObjectsAtResourcePath:[someURL absoluteString] objectMapping:objectMapping delegate:self]

From the another stackoverflow thread (http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using-restkit), I know how to do a simple POST request with the following code:

RKClient *myClient = [RKClient sharedClient];
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

//User and password params
[params setObject:password forKey:@"password"];
[params setObject:username forKey:@"email"];

//The server ask me for this format, so I set it here:
[rpcData setObject:@"2.0" forKey:@"jsonrpc"];
[rpcData setObject:@"authenticate" forKey:@"method"];
[rpcData setObject:@"" forKey:@"id"];
[rpcData setObject:params forKey:@"params"];

//Parsing rpcData to JSON! 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:rpcData error:&error];    

//If no error we send the post, voila!
if (!error){
    [[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send];
}

I was hoping someone would help me marry these two code snippets into a workable solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剑心龙吟 2025-01-10 19:33:17

要发布对象,我所做的是将路径关联到对象。然后使用RKObjectManager中的postObject方法。

我假设您已经配置了 RestKit,因此您已经设置了基本路径,并为您的 CDIssue 定义了对象映射,就像您在已有的代码中一样。考虑到这一点,请尝试以下代码:

//We tell RestKit to asociate a path with our CDIssue class
RKObjectRouter *router = [[RKObjectRouter alloc] init];
[router routeClass:[CDIssue class] toResourcePath:@"/path/to/my/cdissue/" forMethod:RKRequestMethodPOST];
[RKObjectManager sharedManager].router = router;

//We get the mapping for the object that you want, in this case CDIssue assuming you already set that in another place
RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[CDIssue class]];

//Post the object using the ObjectMapping with blocks
[[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) {

    loader.objectMapping = mapping;
    loader.delegate = self;

    loader.onDidLoadObject = ^(id object) {
        NSLog(@"Got the object mapped");
        //Be Happy and do some stuff here
    };

    loader.onDidFailWithError = ^(NSError * error){
        NSLog(@"Error on request");
    };

    loader.onDidFailLoadWithError = ^(NSError * error){
        NSLog(@"Error on load");
    };

    loader.onDidLoadResponse = ^(RKResponse *response) {
        NSLog(@"Response did arrive");
        if([response statusCode]>299){
            //This is useful when you get an error. You can check what did the server returned
            id parsedResponse = [KFHelper JSONObjectWithData:[response body]];
            NSLog(@"%@",parsedResponse);
        }

    };


}];

To post an object what I do is associate a path to an object. Then use the method postObject from RKObjectManager.

I asume that you have already configured RestKit so you have the base path set and defined the object mapping for your CDIssue as you have in the code that you already have. With that in mind try this code:

//We tell RestKit to asociate a path with our CDIssue class
RKObjectRouter *router = [[RKObjectRouter alloc] init];
[router routeClass:[CDIssue class] toResourcePath:@"/path/to/my/cdissue/" forMethod:RKRequestMethodPOST];
[RKObjectManager sharedManager].router = router;

//We get the mapping for the object that you want, in this case CDIssue assuming you already set that in another place
RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[CDIssue class]];

//Post the object using the ObjectMapping with blocks
[[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) {

    loader.objectMapping = mapping;
    loader.delegate = self;

    loader.onDidLoadObject = ^(id object) {
        NSLog(@"Got the object mapped");
        //Be Happy and do some stuff here
    };

    loader.onDidFailWithError = ^(NSError * error){
        NSLog(@"Error on request");
    };

    loader.onDidFailLoadWithError = ^(NSError * error){
        NSLog(@"Error on load");
    };

    loader.onDidLoadResponse = ^(RKResponse *response) {
        NSLog(@"Response did arrive");
        if([response statusCode]>299){
            //This is useful when you get an error. You can check what did the server returned
            id parsedResponse = [KFHelper JSONObjectWithData:[response body]];
            NSLog(@"%@",parsedResponse);
        }

    };


}];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文