RestKitとObjective-Cを使用してオブジェクトへのJSON応答をマッピングする

StackOverflow https://stackoverflow.com/questions/8309543

質問

私はObjective-Cに比較的新しいものであり、RestKitを使用してWebサービスからJSON応答を受け取ろうとしています。私はアプリケーションにデータを正常に受信しました。

{id:"1","Translation":"Test"}

この翻訳をアプリケーションの「翻訳」オブジェクトにマッピングしたいと思いますが、いくつかの異なる方法を試しましたが、これを達成する方法はわかりません。

だから私の質問は次のとおりです。

  1. この応答を翻訳オブジェクトにマップするにはどうすればよいですか
  2. 私はこれを正しく行い、この呼び出しを完了する方法を作成しています。

私の翻訳オブジェクト

@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

}
役に立ちましたか?

解決

コードのスニペットは少し時代遅れのようです。最新を読むことを強くお勧めします オブジェクトマッピングガイド レストキットを最大限の可能性に活用するために - 特に部分 KVCなしでマッピング.

編集:

RestKitでオブジェクトを投稿して回答を返すために、 TranslationRequest 私たちの要求を保持するクラス& Translation 私たちの応答を保持するため。

まず、設定します RKObjectManager およびマッピング(私は通常、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];

これは、必要なセットアップに十分である必要があります。このようなコード(任意のコントローラーなど)のどこにでもバックエンドを呼び出すことができます。

//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ログから判断すると、これは機能するはずです。

他のヒント

返されたJSON文字列をJSONパーサーに渡す必要があります。私が使う sbjson. 。その後、結果の辞書を使用して、オブジェクトのプロパティを入力できます。

RESTKITには、4つの異なるJSONパーサーをカプセル化するネイティブオブジェクトがあるようです。ただし、トップレベルの解析されたオブジェクトは常に辞書になると想定しているように見えるので、注意することをお勧めします。

別の方法として、あなたの質問の例はJSON有効ではありません。このように見えるはずです:

{"id":"1","Translation":"Test"}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top