如何在数组属性中创建 RequestDescriptor (iOS RestKit)

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

这里是 api 请求定义(json 格式示例):

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

这里有两个class in object-c:

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

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

我想提出一个类似

的请求描述符
// 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];

有个问题,当我通过RKObjectManagerpost时,服务器收到我的post总是

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

位置数组值似乎没有正确映射,有什么问题吗?

最后我发现根本原因只是请求的 mime 类型设置。当我使用时:

[[RKObjectManager sharedManager] setRequestSerializationMIMEType:RKMIMETypeJSON];

一切顺利! ;)