我正在使用Restkit 0.20.x来映射来自json的对象,如
{
"d":{
"results":[
{
"Web":[
"key1":"value1",
"key2":"value2"
],
"Image":[
"key1":"value1",
"key2":"value2"
],
},
],
},
}
我的主要目的是管理“Web”和“图像”键。 我正在尝试映射对象但坚持“结果”键(键“结果”的值是一个只有一个元素作为字典的数组)。 在我的案例中如何使用RestKit映射对象?
我的失败工具:
WFSD.h
@interface WFSD : NSObject
@property (nonatomic, strong) WFSResults *results;
@end
WFSResults.h
@interface WFSResults : NSObject
@property (nonatomic, strong) WFSResult *result;
@end
WFSResult.h
@interface WFSResult : NSObject
@property (nonatomic, strong) WFSWeb *web;
@property (nonatomic, strong) WFSImage *image;
@end
MyController.m
RKObjectMapping* dMapping = [RKObjectMapping mappingForClass:[WFSD class]];
RKObjectMapping* resultsMapping = [RKObjectMapping mappingForClass:[WFSResults class]];
RKRelationshipMapping* rsMapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"results" toKeyPath:@"results" withMapping:resultsMapping];
[dMapping addPropertyMapping:rsMapping1];
RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[WFSResult class]];
[resultsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil toKeyPath:@"result" withMapping:resultMapping]];
RKRelationshipMapping* rsMapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"Image" toKeyPath:@"Image" withMapping:imageMapping];
[resultMapping addPropertyMapping:rsMapping2];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dMapping
pathPattern:nil
keyPath:@"d"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
答案 0 :(得分:2)
请注意从模型类中删除WFSResults
。实际上它只是WFSResult
个对象的列表,因此您应该将其建模为:
@interface WFSD : NSObject
@property (nonatomic, strong) NSArray *results;
@end
您还需要查看WFSResult
,因为JSON中的Web
和Image
也是数组。所以我希望看到:
@interface WFSResult : NSObject
@property (nonatomic, strong) NSArray *web;
@property (nonatomic, strong) NSArray *image;
@end
通过这种方式,RestKit可以在映射期间创建对象,然后它有一个数组来存储对象列表。