我从我的网络服务中获得了以下 JSON:
"GasPrices":{
"Ai92":{
"Price":30.1000,
"LastDate":"\/Date(1385337600000)\/",
"Votes":0
},
"Ai95":{
"Price":33.2000,
"LastDate":"\/Date(1385337600000)\/",
"Votes":0
}
我想将其映射到 NSDictionary
,其键是 NSString
,值是我的自定义类,例如 PriceInfo
.
我现在使用默认设置得到的是 NSDictionary,其值也是 NSDictionaries。
如何实现所需的映射?
UPD。这是我现在的完整设置。
@interface FillingStation : NSObject
@property (nonatomic, strong) NSNumber *uid;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSDictionary *fuelPrices;
@end
@interface PriceInfo : NSObject
@property (nonatomic, strong) NSNumber *price;
@property (nonatomic, strong) NSDate *lastDate;
@property (nonatomic, strong) NSNumber *votes;
@end
配置映射:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[FillingStation class]];
[mapping addAttributeMappingsFromDictionary:@{
@"Id" : @"uid",
@"Title" : @"title",
@"GasPrices" : @"fuelPrices"
}];
这导致 fuelPrices
是 NSDictionary
,结构如下:
NSString -> NSDictionary,
NSString -> NSDictionary,
...
我希望它是:
NSString -> PriceInfo,
NSString -> PriceInfo,
...
而且我不需要 FillingStation
中有一个中间字典,然后我可以手动映射它。
最佳答案
好吧,看来我找到了答案。不完全是我想要的,但对我来说可以接受:https://github.com/RestKit/RestKit/wiki/Object-Mapping#handling-dynamic-nesting-attributes
我必须向 PriceInfo
类添加另一个属性,并将 fuelPrices
从 NSDictionary
更改为 NSSet
(NSArray
也可以工作,但我不需要排序),所以它变成了:
@interface FillingStation : NSObject
@property (nonatomic, strong) NSNumber *uid;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSSet *fuelPrices;
@end
@interface PriceInfo : NSObject
@property (nonatomic, strong) NSString *fuelType;
@property (nonatomic, strong) NSNumber *price;
@property (nonatomic, strong) NSDate *updateDate;
@property (nonatomic, assign) NSUInteger votes;
@end
我的映射现在看起来像这样:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[FillingStation class]];
[mapping addAttributeMappingsFromDictionary:@{
@"Id" : @"uid",
@"Title" : @"title"
}];
RKObjectMapping *priceInfoMapping = [RKObjectMapping mappingForClass:[PriceInfo class]];
[priceInfoMapping setForceCollectionMapping:YES];
[priceInfoMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"fuelType"];
[priceInfoMapping addAttributeMappingsFromDictionary:@{
@"(fuelType).Price": @"price",
@"(fuelType).LastDate": @"updateDate",
@"(fuelType).Votes": @"votes"
}];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"GasPrices"
toKeyPath:@"fuelPrices"
withMapping:priceInfoMapping]];
关于ios - RestKit:使用特定类型的值映射到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407370/