RestKit:映射JSONstring数组

鉴于以下JSON:

{ "someKey":"someValue", "otherKey":"otherValue", "features":[ "feature1", "feature2", "feature3" ] } 

我使用RKMapperOperationRKEntityMapping将这个JSON映射到NSManagedObject (在这个例子中,我将有2个实体映射:一个用于顶层对象,另一个用于我的Feature类)。

顶级对象映射是微不足道的:两个属性映射加上与特征关系的关系(特征)。

我的问题是,如何将functionJSON数组映射到一个Feature对象的数组? Feature类只有一个属性name ,我想在其中存储“feature1”,“feature2”等,并加上对父对象(顶层)的引用。 像这样的东西:

 @interface Feature : NSManagedObject //In the implementation file both properties are declared with @dynamic. @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) MyTopLevelObject *myTopLevelObject; @end 

任何想法?

你需要使用一个零键path:

 RKEntityMapping *featureMapping = [RKEntityMapping mappingForEntityForName:...]; [featureMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"name"]]; featureMapping.identificationAttributes = @[ @"name" ]; 

然后,在顶层对象映射上,定义关系:

 [topMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"features" toKeyPath:@"features" withMapping:featureMapping]]; 

在你的特性中(在模型中), myTopLevelObject应该被定义为顶层对象的双向关系。

如果您使用的是Restkit 0.20+,那么您只需要将表示实体的string数组的属性设置为Transformable即可。

例如,在这种情况下,您的Feature实体具有3个属性:

 someKey - String otherKey - String features - Transformable 

Restkit会自动将'features'映射为一个string数组。

所以一旦映射,访问features数组中的一个string就像下面这样简单:

[Feature.features objectAtIndex:?]

我只是试了一下,它完美的作品。

我不认为你可以像这样映射一个string数组到一个ManagedObject中。 但是,由于Feature只有一个name属性,因此您可以将其作为数组存储到MyTopLevelObject 。 您可以通过在Transformabletypes的数据模型MyTopLevelObject features属性添加到MyTopLevelObjectMyTopLevelObject 。 RestKit会自动用NSStrings分析一个NSArray的特性。 然后你可以得到如下function:

 MyTopLevelObject *topLevelObject = ... // get the object from the persistent store NSArray *features = (NSArray*)topLevelObject.features; // this will contain the features as NSString objects