objective C语言 RestKit 0.2返回一个对象数组而不是一个对象



我使用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。

您的映射稍微偏离了。你得到3个对象的原因是你把两个映射都添加到映射提供者。"orderitems"是空集的原因是它不知道如何查找orderitems。

我不知道它是否有效,但我会尝试以下方法。不要将oiMapping添加到映射提供程序中。而不是:

[takeOrderResultMapping mapRelationship:@"orderitems" withMapping:oiMapping];

试题:

[takeOrderResultMapping addRelationshipMappingWithSourceKeyPath: @"数据。orderitems"映射:oiMapping];

最新更新