我正在使用RestKit 0.20时遇到了一个问题,无法映射以下JSON有效载荷。
我试图将产品及其附件作为包含以下对象的数组进行映射。由于此应用程序未使用Core Data,因此我不使用RKEntityMapping,只是使用RKObjectMappings。我已经查阅了RestKit Wiki上有关对象映射的文档,并查看了源代码中类似设置的测试案例,但没有找到解决方案。
{
"Result": {
"Product": {
"Name": "Evil Stuff",
"Description": "Its EVIL!",
"Attachments": [
{
"Id": "c4277b8f-5930-4fee-a166-b5f311d3a353",
"Name": "commands_to_recreate_db.txt",
"Type": "Contraindications"
},
{
"Id": "be4d2e2e-cb3e-48d2-9c7a-fbfddea3a1be",
"Name": "json.txt",
"Type": "Medication Guide"
}
]
},
"Company": {
"Name": "Omni Consumer Products",
"AddressLine1": "100 Evil Dr.",
"AddressLine2": null,
"AddressLine3": null,
"City": "MARS",
"State": null,
"Zip": "10000",
"Country": null,
"PhoneNumber1": "555-555-5555",
"PhoneNumber2": null,
"PhoneNumber3": null,
"FaxNumber": null,
"WebSite": null,
"Email": null
},
"Representatives": []
},
"Messages": [],
"Success": true
}
@interface clinProduct : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSArray *attachments;
@interface clinAttachment : NSObject
@property (strong, nonatomic) NSString *attachmentID;
@property (strong, nonatomic) NSString *attachmentName;
@property (strong, nonatomic) NSString *type;
这是我的对象映射和RKResponseDescriptor:
RKObjectMapping *attachmentMapping = [RKObjectMapping mappingForClass:[clinAttachment class]];
[attachmentMapping addAttributeMappingsFromDictionary:@{@"Id" : @"attachmentID",
@"Name" : @"attachmentName",
@"Type" : @"type"}];
RKObjectMapping *productMapping = [RKObjectMapping mappingForClass:[clinProduct class]];
[productMapping addAttributeMappingsFromDictionary:@{@"Description" : @"description",
@"Name" : @"name"}];
RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"Attachments"
toKeyPath:@"attachments"
withMapping:attachmentMapping];
[productMapping addPropertyMapping:relationshipMapping];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productMapping
pathPattern:nil
keyPath:@"Result.Product"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
我得到了一个有效的响应,但奇怪的是它只映射了产品的描述属性,甚至没有映射它的名称!
2013-03-05 18:39:49.775 iOS[38965:c07] Loaded results: <RKMappingResult: 0x96a8950, results={
"Result.Product" = "Its EVIL!";
当我添加第二个响应描述符,并深入到Result.Product.Attachments中时,仅使用附件响应描述符就可以轻松获取附件数组。非常感谢任何帮助,我已经在自己解决这个问题上花费了很多时间。对于代码块的过长,表示歉意,但是不带所有组件描述完整的RestKit设置很难描述。谢谢。