2011-05-20 64 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