gpt4 book ai didi

ios - 使用 RestKit 将 JSON "Associative array"映射到 CoreData

转载 作者:行者123 更新时间:2023-11-29 03:52:15 25 4
gpt4 key购买 nike

我需要使用 RestKit(iOS) 映射 JSON 对象关联数组。它看起来像具有属性 135,145,423 的对象以及其上的对象。

{
"135": {
"name" : "Object1",
"property1" : "Value1",
"anotherProperty1" : "Value2"
},
"145": {
"name": "Object2",
"property1" : "Value1",
"anotherProperty1" : "Value2"
},
"423": {
"name": "Object3",
"property1" : "Value1",
"anotherProperty1" : "Value2"
}
}

我已经获得了有效的单个对象的映射。映射执行到 CoreData。我唯一的解决方案是将关联数组转换为普通数组并将数字放入“id”字段,但我认为这不是一个优雅的解决方案。

有没有正确的方法可以直接使用 RestKit 执行此类映射?

最佳答案

这是针对我的情况的解决方案。

NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx

// 1. Create dynamic mapping
RKDynamicMapping* dynamicMapping = [[RKDynamicMapping alloc] init];
// 2. Process every entry separately
dynamicMapping.forceCollectionMapping = YES;

// 3. Set mappings for every object
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
// 4. Mapping to Core Data (Can be replaced with RKObjectMapping if there's no need of CodeData)
RKEntityMapping *singleRouteMapping = [RKEntityMapping mappingForEntityForName:@"Object" inManagedObjectStore:managedObjectStore];
// 5. Walking through all keys (but with dynamicMapping.forceCollectionMapping = YES) there'll be only one. It's better to refactor it.
for (NSString *key in representation) {
// 6. Set mappings for every property exect 'id'
[singleRouteMapping addAttributeMappingsFromDictionary:@{
[NSString stringWithFormat: @"%@.name", key]: @"name",
[NSString stringWithFormat: @"%@.property1", key]: @"property1",
[NSString stringWithFormat: @"%@.anotherProperty1", key]: @"anotherProperty1"
}];
}
// 7. Map 'id' property at last
[singleRouteMapping addAttributeMappingFromKeyOfRepresentationToAttribute: @"id"];

return singleRouteMapping;
}];

RKResponseDescriptor *pluralDescriptor = [RKResponseDescriptor responseDescriptorWithMapping: dynamicMapping
pathPattern: @"/api/objects"
keyPath: nil
statusCodes: statusCodes];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.somesite.com/api/objects"]];
RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[pluralDescriptor]];

关于ios - 使用 RestKit 将 JSON "Associative array"映射到 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16955880/

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