restkit 10.0中的RKObjectMapping映射问题

时间:2012-04-19 11:17:59

标签: ios json web-services restkit

我对新的restkit 10.0中的RKObjectMapping感到困惑。 我用RKClient调用了我的web服务,并以JSON的形式得到了响应。 现在我想用我的User类映射JSON字符串。 怎么做?

  

块引用   {“id”:2,“displayName”:“Giri Bhushan”,“roles”:null,“username”:“FBUser-123456”,“password”:“dddddddddddddddddd = \ r \ n”,“email”:“ test@gmail.com”, “性别”: “M”, “生日”:空, “朋友”:空, “bloodGroup”:空, “名字”:空, “姓氏”:空, “phoneNumber的”:空}

我尝试使用以下代码:

  

RKObjectMapping * userMapping = [RKObjectMapping mappingForClass:[User class]];       [userMapping mapKeyPath:@“id”toAttribute:@“userId”];

[userMapping mapKeyPath:@"displayName" toAttribute:@"displayName"];
[userMapping mapKeyPath:@"userName" toAttribute:@"userName"];
[userMapping mapKeyPath:@"password" toAttribute:@"password"];
[userMapping mapKeyPath:@"email" toAttribute:@"email"];
[userMapping mapKeyPath:@"gender" toAttribute:@"gender"];
[userMapping mapKeyPath:@"birthDate" toAttribute:@"birthDate"];
[userMapping mapKeyPath:@"bloodGroup" toAttribute:@"bloodGroup"];
[userMapping mapKeyPath:@"firstName" toAttribute:@"firstName"];
[userMapping mapKeyPath:@"lastName" toAttribute:@"lastName"];

[userMapping mapKeyPath:@"phoneNumber" toAttribute:@"phoneNumber"];

[[RKObjectManager sharedManager].mappingProvider setMapping:userMapping forKeyPath:@"user"];

但是,如何使用RKObjectMapping映射JSON字符串?

2 个答案:

答案 0 :(得分:0)

如果您在JSON的根级别有用户,则以下内容应该有效:

RKObjectManager *manager = [RKObjectManager sharedManager];
RKManagedObjectMapping *userMapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:manager.objectStore];
[userMapping mapKeyPath:@"id" toAttribute:@"userId"];
[userMapping mapAttributes:@"displayName",@"userName",@"password", nil]; // Add other attributes
[manager.mappingProvider setMapping:userMapping forKeyPath:@""];

答案 1 :(得分:0)

你错过了这一行:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"" delegate:self];

然后实现其委托方法,如:
(void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects{ NSLog(@"Objects Retrieved: %d\n%@", objects.count, objects);
YourObject* obj = [objects objectAtIndex:0];

NSString* info = [NSString stringWithFormat:
                  @"Value 1 is %@\n"
                  @"Value 2 is %@\n"
                  @"Value 3 is: %@",
                  [obj value1],
                  [obj value2],
                  [obj value3];

}`

希望这适合你。 XD