RestKit: mapping JSON array of strings

后端 未结 3 1439
甜味超标
甜味超标 2020-12-30 18:14

Given the following JSON:

{
   \"someKey\":\"someValue\",
   \"otherKey\":\"otherValue\",
   \"features\":[
      \"feature1\",
      \"feature2\",
      \"f         


        
相关标签:
3条回答
  • 2020-12-30 18:18

    You need to use a nil key path:

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

    Then, on your top level object mapping, define the relationship:

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

    In your feature (in the model), myTopLevelObject should be defined as a bi-directional relationship to the top level object.

    0 讨论(0)
  • 2020-12-30 18:20

    I don't think you can map an array of strings into a ManagedObject like that. However, since Feature only has one name property you could just store it as an array into your MyTopLevelObject. You can do that by adding a features property to MyTopLevelObject in your datamodel with the type Transformable. RestKit will automatically parse the features a NSArray with NSStrings. You can then get the features as following:

    MyTopLevelObject *topLevelObject = ... // get the object from the persistent store
    NSArray *features = (NSArray*)topLevelObject.features; // this will contain the features as NSString objects
    
    0 讨论(0)
  • 2020-12-30 18:23

    If you are using Restkit 0.20+ then all you need to do is set the property that is representing the string array of your entity to Transformable.

    For example, in this case your Feature entity has 3 properties:

    someKey - String
    otherKey - String
    features - Transformable
    

    Restkit will automatically map 'features' as a string array.

    So once mapped, to access one of the strings in the features array would be as simple as:

    [Feature.features objectAtIndex:?]

    I just tried it and it works perfect.

    0 讨论(0)
提交回复
热议问题