objective-c - 如何在通过 RESTKIT 映射之前更改 JSON

标签 objective-c json mapping restkit

我正在使用 RESTKIT 映射从服务器返回的 JSON。

从服务器获取的JSON结果如下

{"term":"Zh","results":{"users":[{"id":{"$oid":"4ebe59970a614e0019000055"},"term":"some text","score":1}]}

如何将上面的 JSON 结果转换为下面的结果:

{"results":{"users":[{"uid":"4ebe59970a614e0019000055","text":"some text"}]}

此外,我在哪里可以执行此操作,以便 RESTKIT 映射使用转换后的 JSON 而不是初始的 JSON?

下面是我用来管理 JSON 和映射的加载器类

-(void)getObjects
{
    RKObjectManager *sharedManager = [RKObjectManager sharedManager];
    [sharedManager loadObjectsAtResourcePath:self.resourcePath delegate:self];
}

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
    NSLog(@"Loaded PAYLOAD successfully for %@, with response %@", self.resourcePath , [response bodyAsString]  );
}


- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects 
{
}


+ (void)setManagerAndMappings
{
    RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:SERVER_URL];
    RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease];

    //User Object Mapping
    RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[User class]];
    [userMapping mapKeyPath:@"_id" toAttribute:@"uid"];

    [userMapping mapAttributes:@"avatar_url",@"created_at",@"email",@"name",@"nickname",@"follower_count",@"following_count",@"answer_count",@"new_notification_count",@"new_questions_count",@"is_following",@"facebook_configured",@"twitter_configured",@"description",@"approved",@"type", nil];
    [provider setMapping:userMapping forKeyPath:@"user"];

}

最佳答案

@Shocks 的回答很吸引人,不幸的是它对 0.20 之前的版本有效。

无论如何,类似的解决方案也可用于 0.20,使用 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

关于objective-c - 如何在通过 RESTKIT 映射之前更改 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8692246/

相关文章:

objective-c - EncodeInt64 和 DecodeInt64 适用于无符号整数吗?

objective-c - NSWorkspace共享工作空间运行应用程序导致内存泄漏;另一种选择?

c++ - OpenCV 透视校正和裁剪

javascript - 如何将表单中的数据发布到本地 JSON 文件?

json - 如何在 Stringbody 中传递 json 字符串以及 Ga特林中的动态值?

ios - iOS 和 OSX 使用相同的 Objective-C 运行时吗?

c - 序列化时需要JSON

Python 将多个对象加载到映射中以在内存缓存中使用

python - 使用 lambda 映射带有 *args 的函数

javascript - 如何将 Object.keys().map() 函数中的参数设置为新对象中的键?