4

给定以下 JSON:

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

我用 and 将这个 JSON 映射到sNSManagedObject中(在这个例子中,我将有 2 个实体映射:一个用于顶级对象,另一个用于我的要素类)。RKMapperOperationRKEntityMapping

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

我的问题是,如何将要素 JSON 数组映射到要素对象数组中?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

任何想法?

4

3 回答 3

7

您需要使用 nil 密钥路径:

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

然后,在您的顶级对象映射中,定义关系:

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

在您的特征中(在模型中),myTopLevelObject应定义为与顶级对象的双向关系。

于 2013-06-19T10:42:30.687 回答
7

如果您使用的是 Restkit 0.20+,那么您需要做的就是将表示实体的字符串数组的属性设置为 Transformable。

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

someKey - String
otherKey - String
features - Transformable

Restkit 会自动将“功能”映射为字符串数组。

因此,一旦映射,访问 features 数组中的字符串之一将非常简单:

[Feature.features objectAtIndex:?]

我刚试了一下,效果很好。

于 2014-01-20T21:52:03.893 回答
1

我认为您不能将字符串数组映射到这样的 ManagedObject 中。但是,由于 Feature 只有一个name属性,您可以将其作为数组存储到您的MyTopLevelObject. 你可以通过在你的数据模型中添加一个类型为 的features属性来做到这一点。RestKit 将使用 NSStrings 自动解析 NSArray 的特征。然后,您可以获得以下功能:MyTopLevelObjectTransformable

MyTopLevelObject *topLevelObject = ... // get the object from the persistent store
NSArray *features = (NSArray*)topLevelObject.features; // this will contain the features as NSString objects
于 2013-06-19T10:06:29.330 回答