使用RestKit和Objective-C将JSON响应映射到对象 [英] Mapping a JSON response to an object using RestKit and Objective-C
问题描述
我对Objective-C相对较新,并且正在尝试使用RestKit从Web服务接收JSON响应.我已成功将数据接收回我的应用程序,看起来像这样查看响应:
I am relatively new to Objective-C and am attempting to use RestKit to receive a JSON response from a web service. I have successfully received the data back to my application, which looks like this viewing the response:
{id:"1","Translation":"Test"}
我想将此翻译映射到我的应用程序中的翻译"对象,但是尝试了几种不同的方法,但不确定如何实现.
I would like to map this translation to my "Translation" object in my application, but have tried a few different ways but am not sure how to achieve this.
所以我的问题是:
- 如何将该响应映射到我的翻译对象
- 我能正确执行此操作吗,创建一种方法来完成此调用,而不是我的视图控制器?
我的翻译对象
@implementation Translation
@synthesize identifier = _identifier;
@synthesize translation = _translation;
- (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
@"id", @"identifier",
@"translation", @"translation",
nil];
}
@end
我的翻译方法
- (NSString *)performTranslation:(NSString *)translation
{
NSString *data = [[NSString alloc] initWithFormat:@"{\"SourceId\": \"%@\",\"RegionTag\": \"%@\",\"InputString\": \"%@\"}", @"1", @"Glasgow", translation];
NSString *post = data;
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://my.url.com/Translation/Translate"]];
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = post;
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];
[MyRequest send];
RKResponse *Response = [MyRequest sendSynchronously];
return Response.bodyAsString; <--- looking to map this to translation object here
}
推荐答案
您的代码段似乎有些过时了.我强烈建议您依次阅读最新的对象映射指南充分利用RestKit的最大潜力-尤其是无需KVC进行映射的部分.
The snippet of your code seems a bit outdated. I strongly recommend reading the newest Object Mapping guide in order to leverage RestKit into it's fullest potential - especially the part Mapping without KVC.
为了使用RestKit发布对象并接收答案,我们定义了一个TranslationRequest
类,该类将保存我们的请求& Translation
保持我们的答复.
In order to post an object with RestKit and receive back an answer, we define a TranslationRequest
class that will hold our request & Translation
to hold our response.
首先,我们设置RKObjectManager
和映射(我通常在AppDelegate中执行此操作):
Firstly, we set up our RKObjectManager
and mappings (i usually do this in my AppDelegate):
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kOurBaseUrl];
[manager setSerializationMIMEType:RKMIMETypeJSON];
//this is a singleton, but we keep the manager variable to avoid using [RKObjectManager sharedManager] all the time
//Here we define a mapping for the request. Note: We define it as a mapping from JSON to entity and use inverseMapping selector later.
RKObjectMapping *translationRequestMapping = [RKObjectMapping mappingForClass:[TranslationRequest class]];
[translationRequestMapping mapKeyPath:@"RegionTag" toAttribute:@"regionTag"];
...
[[manager mappingProvider] setSerializationMapping:[translationRequestMapping inverseMapping] forClass:[TranslationRequest class]];
//now we define the mapping for our response object
RKObjectMapping *translationMapping = [RKObjectMapping mappingForClass:[Translation class]];
[translationMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[translationMapping mapKeyPath:@"Translation" toAttribute:@"translation"];
[[manager mappingProvider] addObjectMapping:mapping];
//finally, we route our TranslationRequest class to a given endpoint
[[manager router] routeClass:[TranslationRequest class] toResourcePath:kMyPostEndpoint];
这足以完成必要的设置.我们可以在代码中的任何地方(例如,在任何控制器中)调用后端,如下所示:
This should be enough of the necessary setup. We can call our backend anywhere in the code (e.g. in any controller) like this:
//we create new TranslationRequest
TranslationRequest *request = [[TranslationRequest alloc] init];
[request setRegionTag:@"Hello"];
....
//then we fetch the desired mapping to map our response with
RKObjectMapping *responseMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:class]
//and just call it. Be sure to let 'self' implement the required RKObjectManagerDelegate protocol
[[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self];]
尝试这种方法,让我知道您是否需要任何帮助..我无法完全测试它,因为我没有任何合适的后端可以返回响应,但是从RestKit日志中判断这应该可行.
Try this approach and let me know if you need any assistance.. I was not able to test it fully as i don't have any suitable backend that will return the responses, but judging from the RestKit log this should work.
这篇关于使用RestKit和Objective-C将JSON响应映射到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!