我正在使用RestKit到我的 iPhone 应用程序中加载国家/地区列表。问题是 elementToPropertyMappings 方法使用字典来映射每个对象。就我而言,我有一个字符串数组,我想将其映射到 Country 类的 name 属性。
有人知道怎么做吗?
elementToPropertyMappings
Must return a dictionary containing mapping from JSON element names to property accessors
- (NSDictionary *)elementToPropertyMappings Declared In 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?
}
最佳答案
找出 RKJSONParser 的正确导入对我来说是最具挑战性的事情。
如果有其他方法可以通过映射类来完成此任务,请告诉我。
这是加载简单数组所涉及的代码。
#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]];
}
关于iphone - RestKit - 加载一个简单的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067778/