0

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

{"id":2,"displayName":"Giri Bhushan","roles":null,"username":"FBUser-123456","password":"dddddddddddddddd=\r\n","email":"test@gmail.com","gender":"M","birthDate":null,"friends":null,"bloodGroup":null,"firstName":null,"lastName":null,"phoneNumber":null}

我试过下面的代码:

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 字符串?

4

2 回答 2

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

于 2012-07-02T16:15:28.457 回答
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:@""];
于 2012-06-06T12:38:41.557 回答