我对 RestKit 框架相当陌生。我在解析一些 JSON 响应时遇到了困难。
{
"success": "1",
"loginStatus": "Success",
"sessionToken": "NTE5YTg5NjE4ZDIxYzQ3YzMUybdtsUU8989GVmaW5lZHwxMzY5ODE0MTc4Mzgw",
"user": {
"ActivationMethod": false,
"ActivationToken": "iey4C5E3iMt7mXZL",
"Active": true,
"FirstName": "John",
"LastName": "Doe",
}
}
这是我的登录网络服务的响应。
我想要的是在一个类中映射 sessionToken、FirstName 和 LastName 的值。为此,我创建了一个类 User
@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
我已经浏览了这个关于对象映射的链接,但可以解决这个问题。
这方面的任何指示都会非常有帮助
问候,
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
登录将用户类的对象作为属性。有什么方法可以通过简单地创建单个对象而不是多个嵌套对象来获取 JSON 响应中所有键的值?