2011-05-20 70 views
6

我使用RestKit進入我的iPhone應用程序來加載一個國家列表。問題是elementToPropertyMappings方法使用字典映射每個對象。在我的情況下,我有一個字符串數組,我想映射到Country Country類的name屬性。RestKit - 加載一個簡單的數組

任何人都知道這是怎麼回事?

elementToPropertyMappings

必須返回一個包含從JSON元素名稱 映射字典來 屬性訪問

  • (的NSDictionary *)宣佈RKObjectMappable.h

elementToPropertyMappings我的JSON數據

["Argentina","Australia","Austria","Belgium","Bolivia","Brazil","Bulgaria","Canada","Cayman Islands","China","Costa Rica","Croatia","Czech Republic","Denmark","Ecuador","Ethiopia","F.Y.R.O. Macedonia","Finland","France","French Polynesia","Germany","Guam","Hong Kong SAR","Indonesia","Ireland","Israel","Italy","Japan","Latvia","Lithuania","Luxembourg","Malaysia","Malta","Mexico","Morocco","Netherlands","New Zealand","Nicaragua","Norway","Papua New Guinea","Peru","Poland","Portugal","Puerto Rico","Qatar","Romania","Russia","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sweden","Switzerland","Taiwan","United Arab Emirates","United Kingdom","United States","Venezuela","Vietnam"] 

UPDATE:

我想通了如何使用RKClient提出請求,因此映射功能被跳過。現在我需要弄清楚什麼類用於JSON解析。 yajl-objc解析器看起來不錯,但我不想包含另一個解析器,如果它可以用RestKit中的一個庫來完成的話。

-(void)loadLocations 
{ 
    NSLog(@"loadLocations"); 
    RKObjectManager *objectManager = [RKObjectManager sharedManager];  
    [[RKClient sharedClient] get:@"/locations/countries.json" delegate:self]; 

} 

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { 
    NSLog(@"Loaded payload: %@", [response bodyAsString]); 
// HOW CAN I PARSE THIS STRING INTO AN NSArray? 
} 

回答

8

找出RKJSONParser的正確導入對我來說是最具挑戰性的事情。

如果還有其他方法可以通過Mapping類完成此任務,請讓我知道。

以下是加載簡單數組時涉及的代碼。上v0.10加入

#import <RestKit/Support/RKJSONParser.h> 
@implementation CountriesViewController 
@synthesize countries; 

-(void)loadLocations 
{ 
    NSLog(@"loadLocations");  
    [[RKClient sharedClient] get:@"/locations/countries.json" delegate:self]; 
} 

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { 
    NSLog(@"Loaded payload: %@", [response bodyAsString]); 
    RKJSONParser* parser = [RKJSONParser new]; 
    countries = [parser objectFromString:[response bodyAsString]]; 
} 
+3

對於v0.9.3導入應'#進口'如果你也可以使用'[response parsedBody]' – 2011-08-28 18:25:28

+2

,而對於當前版本(0.10),你應該使用'#import '與'RKJSONParserJSONKit'對象代替'RKJsonParser' – 2012-05-25 11:37:49

0

支持字符串數組:Source