Search code examples
iosobjective-crestkit

How to make a RequestDescriptor within array attribute (iOS RestKit)


Here is the api request definition (json format sample):

{"Name":"my name", "Location":[{"Lon":123.4563, "Lat":22.3333},{"Lon":133.1553, "Lat":12.2111}]}

Here is two class in object-c:

@interface MyLocation : NSObject
@property (nonatomic, strong) NSNumber* lat;
@property (nonatomic, strong) NSNumber* lon;
@end

and

@interface MyRequest : NSObject
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSMutableArray<MyLocation*> *locations;
@end

I wanna make a requestdescriptor like

// MyLocation attribute mapping
RKObjectMapping* attrMapping = [RKObjectMapping mappingForClass:[MyLocation class]];
[attrMapping addAttributeMappingsFromDictionary:@{@"Lon":@"lon", @"Lat":@"lat"}];
RKRelationshipMapping *relatedMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"Location" toKeyPath:@"locations" withMapping:attrMapping];

// inverse mapping for requestDescriptor
Class class = [MyRequest class];
RKObjectMapping* reqMapping = [RKObjectMapping mappingForClass:class];
[reqMapping addAttributeMappingsFromDictionary:@{@"Name":@"name"}];
[reqMapping addPropertyMapping:relatedMapping];
RKRequestDescriptor *reqDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[reqMapping inverseMapping] objectClass:class rootKeyPath:nil method:RKRequestMethodPOST];

There is a question, when I post by RKObjectManager, the server receive my post always is

    {"Name":"my name", "Location":[]}

Location array value seems not be correctly mapped, does there anything go wrong?


Solution

  • Finally I figured out the root cause is just a the mime type setting of request. while I use :

    [[RKObjectManager sharedManager] setRequestSerializationMIMEType:RKMIMETypeJSON];
    

    Everything goes right! ;)