我正在使用 Restkit 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 个对象的数组。第一个对象是一个带有空集“orderitems”的 TakeOrderResult 实例。接下来的两个对象是 OrderItems 的实例。
如果有人可以帮助我并指出为什么我没有得到 1 个对象,那就太好了,即 TakeOrderResult 的一个实例,其中“orderitems”是一组两个对象/两个 OrderItem。