RestKit:如何在映射之前预处理JSON值

时间:2013-08-29 10:21:37

标签: ios restkit restkit-0.20

目前我使用的是以下JSON格式,这是SharePoint REST服务的一个代码段:

{results:[
   {uri:"https://site.com/_api/Web/Lists(guid'43963c38-4d1c-4734-8b2d-22dc0b92908c')"},
   {uri:"https://site.com/_api/Web/Lists(guid'5363c738-7d9d-9774-6b2d-52dc0b93903d')"}]
}

我有以下对象映射:

RKEntityMapping *listMapping = [RKEntityMapping mappingForEntityForName:@"SPList" 
    inManagedObjectStore:managedObjectStore];
[listMapping addAttributeMappingsFromDictionary:@{
    @"uri":      @"guid"}];
listMapping.identificationAttributes = @[@"guid"];

但是,在保存到guid之前,我想添加逻辑以便在保存之前仅从uri检索guid部分,因此只有“43963c38-4d1c-4734-8b2d-22dc0b92908c”存储在guid字段中。我不知道在哪里添加那个逻辑,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

如果在映射之前需要更改返回的JSON,可以使用RKSerialization的实现:

@interface ORRKJsonSerialization : NSObject <RKSerialization>
@end

并实施

@implementation ORRKJsonSerialization

+ (id)objectFromData:(NSData *)data error:(NSError **)error
{
    id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];
    // change your data before mapping
    return result;
}

+ (NSData *)dataFromObject:(id)object error:(NSError **)error
{
    return [NSJSONSerialization dataWithJSONObject:object options:0 error:error];
}

@end

然后在设置期间:

[RKMIMETypeSerialization registerClass:[ORRKJsonSerialization class] forMIMEType:@"application/json"];

HTH