【发布时间】:2014-02-25 13:50:00
【问题描述】:
我在尝试将 JSON 映射到一个对象结构中时遇到了一些困难:
- Group
+ label
+ type
+ children
- childname1
+ label
+ type
+ value
- childname2
+ label
+ type
+ value
我确实有一个Groupclass
@interface CameraGroup : NSObject
@property (nonatomic, copy) NSString *label;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSDictionary *children;
@end
还有一个Child 类
@property (nonatomic, copy) NSString *label;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSString *value;
我的 JSON 如下所示:
{
"actions": {
"label": "Action List",
"type": "section",
"children": {
"action1": {
"label": "This is action1",
"type": "toggle",
"value": 0
},
"action2": {
"label": "This is action2",
"type": "range",
"value": 0
},
"action3": {
"label": "This is action3",
"type": "toggle",
"value": 0
}
}
}
}
我试图以单个组对象结束,使用 RestKit 持有一个带有键值对动作的 NSDictionary(子对象)(例如 action1 = 标签、类型和值的键和子对象)。
我正在使用以下 sn-p 但总是以一个单一的空子对象结束:
RKObjectMapping *mappingChild = [RKObjectMapping mappingForClass:[Child class]];
[mappingSetting addAttributeMappingsFromDictionary:@{
@"label": @"label",
@"type": @"type",
@"value": @"value"
}];
RKObjectMapping *mappingGroup = [RKObjectMapping mappingForClass:[Group class]];
[mappingGroup addAttributeMappingsFromDictionary:@{
@"label": @"label",
@"type": @"type"
}];
[mappingGroup addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"children" toKeyPath:@"children" withMapping:mappingSetting]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mappingGroup method:RKRequestMethodAny pathPattern:@"/action" keyPath:@"actions" statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.178.1:1337/actions"]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
Group *group = [result firstObject];
NSLog(@"Mapped the group: %@ of type %@ with children %i", article.label, article.label, [group.children count]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Failed with error: %@", [error localizedDescription]);
}];
[operation start];
那么有没有办法在不知道“action1”被命名为“action1”的情况下映射 NSDictionary 部分??
【问题讨论】:
标签: ios objective-c json restkit restkit-0.20