gpt4 book ai didi

ios - RestKit:映射到具有特定类型值的 NSDictionary

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:09:06 27 4
gpt4 key购买 nike

我从我的网络服务中获得了以下 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"
}];

这导致 fuelPricesNSDictionary 结构:

NSString -> NSDictionary,
NSString -> NSDictionary,
...

我希望它是:

NSString -> PriceInfo,
NSString -> PriceInfo,
...

而且我不想要 FillingStation 中的中间字典,然后我可以手动映射它。

最佳答案

好的,看来我找到了答案。不完全是我想要的,但我可以接受:https://github.com/RestKit/RestKit/wiki/Object-Mapping#handling-dynamic-nesting-attributes

我必须向 PriceInfo 类添加另一个属性,并将 fuelPricesNSDictionary 更改为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com