Kalel Wade
Kalel Wade

Reputation: 7792

RestKit - map dynamic attributes to key value pair

I am looking to map the following JSON using restkit.

"ObjectDetails":
[
  {
    "ObjectName":"Test1",
    "Properties":
    {
      "PropertyName1":1,
      "PropertyName3":2
    }
  },
  {
    "ObjectName":"Test2",
    "Properties":
    {
      "PropertyName1":1,
      "PropertyName2":"asdf"
    }
  },
  {
    "ObjectName":"Test3",
    "Properties":
    {
      "PropertyName1":1,
      "PropertyName6":3423,
      "PropertyName7":"test",
      "PropertyName3":2
    }
  }
]

Object

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
//????
@end

Mapping

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[ObjectDetail class]];
[mapping addAttributeMappingsFromDictionary:@{@"ObjectName":@"objectName"}];

RKResponseDescriptor *rd = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:nil keyPath:@"ObjectDetails" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

My issue is that the 'Properties' has dynamic attributes. I haven't found a way to map properties to anything. Ideally, it would be nice to map Properties to a key/value dictionary. I do need the field name as well as the value.

ie.

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
@property (nonatomic, strong) NSMutableDictionary *properties;
@end

Does anyone know a solution for this or have an idea of how to implement it?

UPDATE: Based on @Idali solution, it was very simple. Make sure to upvote their answer if you found this helpful!

Object

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
@property (nonatomic, strong) id *properties;
@end

Mapping

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[ObjectDetail class]];
[mapping addAttributeMappingsFromDictionary:@{@"ObjectName":@"objectName", @"Properties": @"properties"}];

Then just cast it.

self.myDictionnay  = (NSDcitionnary*) objectDetail.properties;

Upvotes: 0

Views: 394

Answers (1)

Idali
Idali

Reputation: 1023

you can resolve it by setting "properties" attribute as transformable type in coredata and declare it as id in your ObjectCalss and map it. If you create ManagedObject subclass it will be as:

@property (nonatomic, retain) id properties;

to read content you can cast it: .... ....

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; ObjectDetail* objectDetail =[fetchedObjects firstObject]; self.myDictionnay = (NSDcitionnary*) objectDetail.properties; NSArray* keys = [self.myDictionnay allKeys]; //to check for existence of any key

Upvotes: 1

Related Questions