使用RestKit进行对象映射

时间:2013-05-29 09:07:42

标签: objective-c restkit

我是RestKit框架的新手。我在解析一些JSON响应方面遇到了困难。

{
    "success": "1",
    "loginStatus": "Success",
    "sessionToken": "NTE5YTg5NjE4ZDIxYzQ3YzMUybdtsUU8989GVmaW5lZHwxMzY5ODE0MTc4Mzgw",
    "user": {
        "ActivationMethod": false,
        "ActivationToken": "iey4C5E3iMt7mXZL",
        "Active": true,
        "FirstName": "John",
        "LastName": "Doe",
}
}

这是我的登录网络服务的回复。

我想要的是将sessionToken,FirstName和LastName的值映射到一个类中。为此,我创建了一个用户类

@interface User : NSObject

@property (nonatomic, strong) NSString* firstName;
@property (nonatomic, strong) NSString* lastName;
@property (nonatomic, strong) NSString* sessionToken;

@end

对于我尝试过以下代码的映射:

  RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class]];
  [mapping addAttributeMappingsFromDictionary:@{
   @"FirstName": @"firstName",
   @"LastName": @"lastName",
   @"sessionToken" : @"sessionToken",
   }];

 RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:@"/login" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

  [objectManager addResponseDescriptor:responseDescriptor];

使用这个我得到Lastname和Firstname的值为null。

网址为http:// [BASE URL] / login

我已经完成了对象映射的link,但可以解决这个问题。

这方面的任何指示都会非常有帮助

此致

tek3

** * ** * ** * 的** * ** 编辑 ** * ** * ** * ** * ****

我现在可以使用下面的代码获取值。

 RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[User class] ];
  [userMapping addAttributeMappingsFromDictionary:@{
   @"FirstName": @"firstName",
   @"LastName": @"lastName",
   }];


  RKObjectMapping* loginMapping = [RKObjectMapping mappingForClass:[Login class] ];
  [loginMapping addAttributeMappingsFromDictionary:@{
   @"sessionToken": @"sessionToken",
   }];

  [loginMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user"
                                                                                 toKeyPath:@"user"
                                                                               withMapping:userMapping]];


  RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:loginMapping pathPattern:@"/login" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

但我仍有一个困惑。我必须创建另一个登录

@interface Login : NSObject

@property (nonatomic, strong) NSString* sessionToken;
@property (nonatomic, strong) User* user;

@end

Login有一个User类的对象作为属性。有没有办法通过简单地创建单个对象而不是多个嵌套对象来获取JSON响应中所有键的值?

1 个答案:

答案 0 :(得分:5)

使用原始映射与单个类,您可以这样做:

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class]];
[mapping addAttributeMappingsFromDictionary:@{
@"user.FirstName": @"firstName",
@"user.LastName": @"lastName",
@"sessionToken" : @"sessionToken",
}];