这是我对 API 的回应:
{"is_favorited":1}
我想用 RestKit 映射它,但我无法让它工作。这是我在 AppDelegate.m 中的:
RKObjectMapping *isFavoriteMapping = [RKObjectMapping mappingForClass:[IsFavorite class]];
[isFavoriteMapping addAttributeMappingsFromDictionary:@{
@"is_favorited" : @"Is_favorited",
}];
RKResponseDescriptor *isFavoriteResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:isFavoriteMapping
method:RKRequestMethodAny
pathPattern:@"/api/isPointFavorited/:sid"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[manager addResponseDescriptor:isFavoriteResponseDescriptor];
路径没问题。我在地址中有 token 。我通过以下方式调用它:
RKObjectManager *manager = [RKObjectManager sharedManager];
[manager getObjectsAtPath: [NSString stringWithFormat:@"/api/isPointFavorited/%@", sid]
parameters:@{
@"pid":[NSString stringWithFormat:@"%@", actualPlace.Id]
}
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
...
}
failure:^(RKObjectRequestOperation *operation, NSError *error)
{
...
}];
我在应用程序中多次使用 RestKit,也使用 sid(登录 token )。所以地址或方法调用都没有问题。问题一定出在映射中,但我不知道该怎么做。我试图将 keyPath 从 nil 更改为 @"is_favorited"但它没有帮助。
我的最爱.h:
@interface IsFavorite : NSObject
@property(nonatomic) NSNumber *Is_favorited;
@end
RestKit 错误:
Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable object representations were found at the key paths searched." UserInfo=0x1849cbc0 {DetailedErrors=(
), NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched: events, results
The representation inputted to the mapper was found to contain nested object representations at the following key paths: is_favorited
This likely indicates that you have misconfigured the key paths for your mappings., NSLocalizedDescription=No mappable object representations were found at the key paths searched., keyPath=null}
编辑 - AppDelegate 中的更改但仍然不起作用:
RKObjectMapping *isFavoriteMapping = [RKObjectMapping mappingForClass:[IsFavorite class]];
[isFavoriteMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"Is_favorited"]];
RKResponseDescriptor *isFavoriteResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:isFavoriteMapping
method:RKRequestMethodAny
pathPattern:@"/api/isPointFavorited/:sid"
keyPath:@"is_favorited"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[manager addResponseDescriptor:isFavoriteResponseDescriptor];
最佳答案
删除 addAttributeMappingsFromDictionary:
的使用,并更改为:
[isFavoriteMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"Is_favorited"]];
然后将响应描述符上的 keyPath 更改为 @"is_favorited"
。
这称为零键路径映射(因为映射中的零源键路径)。
关于iOS RestKit - 映射结果,只有一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225665/