1

我的 JSON 有一个简单的一对多关系,并希望将其映射到对象(不是核心数据实体)中。映射产品工作正常。但是每个产品都有一系列未映射的轨道。

这是 JSON:

在此处输入图像描述

这是代码:

产品.h

#import <Foundation/Foundation.h>

@interface Product : NSObject

@property (nonatomic, strong) NSString* productid;
@property (nonatomic, strong) NSString* title;
@property (nonatomic, strong) NSString* artist;
//...
@property (nonatomic, strong) NSMutableArray *tracks;


轨道.h

#import <Foundation/Foundation.h>

@interface Track : NSObject

@property (nonatomic, strong) NSString *artist;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *mixversion;



这里是请求 JSON 并将响应映射到对象的代码

/// Create Mappers for Product and Track
RKObjectMapping *mappingForProduct = [RKObjectMapping mappingForClass:[Product class]];

[mappingForProduct addAttributeMappingsFromArray:@[@"productid", @"title", @"tracks"]];


RKObjectMapping *mappingForTrack = [RKObjectMapping mappingForClass:[Track class]];
[mappingForTrack addAttributeMappingsFromArray:@[@"artist",@"title",@"mixversion"]];

/// assign relationship product-track
[mappingForProduct addRelationshipMappingWithSourceKeyPath:@"tracks" mapping:mappingForTrack];

/// setup responseDescriptor
NSString *key_path = @"products";
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mappingForProduct
                                                                                   pathPattern:nil
                                                                                       keyPath:key_path
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];


/// Create Manager, connect responseDescriptor and execute
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"myRequestString"]];



[manager addResponseDescriptor:responseDescriptor];
[manager getObject:nil path:@"" parameters:nil
           success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
           {
               self.productsArray = [NSMutableArray arrayWithArray:mappingResult.array];
           }

           failure:^(RKObjectRequestOperation *operation, NSError *error)
           {
               NSLog(@"Error: %@", error);
           }


这给出了一个断言错误:

*** Assertion failure in -[RKObjectMapping addPropertyMapping:],     /Users/.../Pods/RestKit/Code/ObjectMapping/RKObjectMapping.m:235



魔法应该发生在这一行:

[mappingForProduct addRelationshipMappingWithSourceKeyPath:@"tracks" mapping:mappingForTrack];


...但由于某种原因它没有。

我在 SO 和文档上搜索了相当多的资源,尝试了相当多的 keypath 组合更改,但没有任何东西会给出所需的结果。许多可用的示例代码是关于旧版本的 RestKit 或处理核心数据的。我只想获取映射对象,没有核心数据实体。

提前感谢您的任何提示。

4

1 回答 1

1

您只是尝试添加tracks两次映射。它应该是关系映射,而不是属性映射。更改mappingForProduct为:

[mappingForProduct addAttributeMappingsFromArray:@[@"productid", @"title"]];

并且应该消除异常的原因。

于 2013-07-01T15:33:14.803 回答