我使用Restkit Version 0.2将JSON结果映射到Objective-C对象。收到的JSON看起来像这样:
{
"result": {
"errorCode": 0,
"errorMsg": "ok",
"data": {
"orderitems": [
{
"id": "46",
"o_order_id": "15",
"p_product_id": "7",
"t_event_id": "1",
"quantity": "1",
"price": "4.5",
"name": "Name1",
"unit": "something1",
"image": "images/7.png"
},
{
"id": "47",
"o_order_id": "15",
"p_product_id": "10",
"t_event_id": "1",
"quantity": "1",
"price": "3.99",
"name": "Name2",
"unit": "something2",
"image": "images/10.png"
}
]
}
}
}
我定义了以下映射:
RKObjectMapping *oiMapping = [RKObjectMapping mappingForClass:[OrderItem class]];
[oiMapping mapKeyPathsToAttributes:@"p_product_id", @"productID", @"name", @"name", @"t_event_id", @"eventID", @"quantity", @"quantity", nil];
[objectManager.mappingProvider setMapping:oiMapping forKeyPath:@"result.data.orderitems"];
RKObjectMapping *takeOrderResultMapping = [RKObjectMapping mappingForClass:[TakeOrderResult class]];
[takeOrderResultMapping mapKeyPathsToAttributes:@"errorCode", @"errorCode", @"errorMsg", @"errorMessage", nil];
[takeOrderResultMapping mapRelationship:@"orderitems" withMapping:oiMapping];
[objectManager.mappingProvider setMapping:takeOrderResultMapping forKeyPath:@"result"];
takeOrderResultMapping.rootKeyPath = @"result";
[[RKObjectManager sharedManager].mappingProvider setErrorMapping:takeOrderResultMapping];
最后,TakeOrderResult类的定义如下:
@interface TakeOrderResult : NSObject
@property (strong, nonatomic) NSNumber *errorCode;
@property (strong, nonatomic) NSString *errorMessage;
@property (strong, nonatomic) NSSet *orderitems;
@end
这或多或少有用 - 但是,Restkit返回的是3个对象的数组。第一个对象是TakeOrderResult的一个实例,其中包含一个空集“orderitems”。接下来的两个对象是OrderItems的实例。
如果有人可以帮助我并指出为什么我没有得到1个对象,即TakeOrderResult的实例,其中“orderitems”是一组两个对象/两个OrderItems,那将是很好的。