我正在使用 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/