[英]RestKit 0.20: flattening the hierarchy with dynamic in JSON
我正在使用RestKit 0.20,在將包含動態鍵的層次結構的JSON映射到一個對象時遇到問題。
JSON如下所示:
{
"id": 42,
"name": "Name of this entity",
"specialDataMap": {
"2091:10": {
"id": 2091,
"type": "10",
"value": "1'509.49",
"name": "Name of special data type 10"
},
"2091:02" {
"id": 2091,
"type": "02",
"value": "5.5543",
"name": "Name of special data type 02"
}
}
}
並應使用RestKit映射到這樣的對象:
@interface InfoPoint : NSManagedObject
@property (nonatomic, retrain) NSString* identifier;
@property (nonatomic, retrain) NSString* name;
@property (nonatomic, retrain) NSString* valueOfType10;
@property (nonatomic, retrain) NSString* valueOfType02;
@end
如您所見,我不想創建關系並將特殊數據存儲到單獨的對象中。 只是沒有意義。 我想像所有其他屬性一樣將嵌套屬性分配給InfoPoint對象。 通常,這將適用於嵌套對象的關鍵路徑,但是此路徑包含動態部分:“ 2091:10”是ID和ID可能更改的類型的組合(這不是我的“原始”想法,但我有消耗它)。
我已經在RestKit文檔中閱讀了有關處理動態嵌套屬性的信息。 但是我沒有發現它是否以及如何與嵌套屬性一起使用。
-----添加為對評論/問題的答復:----
我也嘗試過使用動態對象映射 。 但這沒有用,因為RestKit似乎對@“ self”目標存在問題:
RKEntityMapping* type10Mapping = [RKEntityMapping mappingForEntityForName:@"InfoPoint" inManagedObjectStore:objectStore];
[type10Mapping addAttributeMappingsFromDictionary:@{
@"value": @"valueOfType10"}];
RKDynamicMapping* dynamicMapping = [[RKDynamicMapping alloc] init];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"specialDataMap" toKeyPath:@"self" withMapping:dynamicMapping]];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if ([[representation valueForKeyPath:@"type"] isEqualToString:@"10"]) {
return type10Mapping;
}
return nil;
}];
您嘗試動態映射不正確。 您應該將動態映射提供給響應描述符。 然后,動態映射應根據在響應中找到的鍵來創建並返回適當的映射。 類似於(徒手書寫)的東西:
RKDynamicMapping* dynamicMapping = [[RKDynamicMapping alloc] init];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
RKEntityMapping* typeMapping = [RKEntityMapping mappingForEntityForName:@"InfoPoint" inManagedObjectStore:objectStore];
[typeMapping addAttributeMappingsFromDictionary:@{
@"id" : @"identifier",
@"name": @"name",}];
NSDictionary *types = [representation valueForKeyPath:@"specialDataMap"];
for (NSString *key in types) {
NSDictionary *type = [[types objectForKey:key] objectForKey:@"type"];
if ([type isEqualToString:@"10"]) {
[typeMapping addAttributeMappingsFromDictionary:@{
[NSString stringWithFormat:@"specialDataMap.%@.value", key]: @"valueOfType10"}];
} else if ...
}
return typeMapping;
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dynamicMapping
pathPattern:...
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.