6

我在我的 iPhone 应用程序中使用RestKit来加载国家列表。问题是 elementToPropertyMappings 方法使用字典来映射每个对象。就我而言,我有一个字符串数组,我想将它们映射到我的 Country 类的 name 属性。

有人知道怎么做吗?

elementToPropertyMappings

必须返回包含从 JSON 元素名称到属性访问器的映射的字典

  • (NSDictionary *)elementToPropertyMappings 在 RKObjectMappable.h 中声明

我的 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"]

更新:

我想出了如何使用 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?
}
4

2 回答 2

8

找出 RKJSONParser 的正确导入对我来说是最具挑战性的事情。

如果有其他方法可以通过 Mapping 类完成此操作,请告诉我。

这是加载简单数组所涉及的代码。

#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]]; 
}
于 2011-05-20T15:30:24.477 回答
0

v0.10 添加了对字符串数组的支持:Source

于 2012-08-23T14:45:35.460 回答