使用 RKObjectManger 而不是 RKClient 来执行 POST。然后,您可以在调用此方法时将响应加载到对象中:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects
编辑(给定 JSON 发送到服务器):
您可以创建自定义模型类,而不是按照您当前的方式创建 JSON。
首先,您可以为您的顶级对象创建一个模型类(假设它被称为用户)。
用户标题
// User.h
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic) int memberId;
@property (nonatomic, copy) NSString *countryCode;
@property (nonatomic, strong) NSArray *contacts;
@end
用户实现
// User.m
#import "User.h"
@implementation User
@synthesize memberId;
@synthesize countryCode;
@synthesize contacts;
@end
然后,您可以创建一个名为 Contact 的模型类。
联系人标题
// Contact.h
#import <Foundation/Foundation.h>
@interface Contact : NSObject
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic) int memberId;
@property (nonatomic) int contactId;
@property (nonatomic, strong) NSString *name;
@end
联系实施
// Contact.m
#import "Contact.h"
@implementation Contact
@synthesize phoneNumber;
@synthesize memberId;
@synthesize contactId;
@synthesize name;
@end
您可以这样使用这些类:
Contact *john = [[Contact alloc] init];
john.phoneNumber = @"+12233333333";
john.memberId = 2222;
john.contactId = 123456;
john.name = @"john";
Contact *mary = [[Contact alloc] init];
mary.phoneNumber = @"+12244444444";
mary.memberId = 3333;
mary.contactId = 123457;
mary.name = @"mary";
User *user = [[User alloc] init];
user.memberId = 1000000;
user.countryCode = @"US";
user.contacts = [NSArray arrayWithObjects:john, mary, nil];
RKObjectMapping *contactsMapping = [RKObjectMapping mappingForClass:[Contact class]];
[contactsMapping mapKeyPath:@"phoneNumber" toAttribute:@"phoneNumber"];
[contactsMapping mapKeyPath:@"memberId" toAttribute:@"memberId"];
[contactsMapping mapKeyPath:@"contactId" toAttribute:@"contactId"];
[contactsMapping mapKeyPath:@"name" toAttribute:@"name"];
RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[User class]];
[objectMapping mapKeyPath:@"memberId" toAttribute:@"memberId"];
[objectMapping mapKeyPath:@"countryCode" toAttribute:@"countryCode"];
[objectMapping mapKeyPath:@"contacts" toRelationship:@"contacts" withMapping:contactsMapping];
//Then you set up a serialization mapping and object mapping and POST it
//This method takes care of both the serialization and object mapping
[[RKObjectManager sharedManager].mappingProvider registerMapping:objectMapping withRootKeyPath:@"user"];
//POST it
[[RKObjectManager sharedManager] postObject:user delegate:self];
在向您展示如何进行序列化映射和 POST 之前,我需要知道您期望什么样的 JSON 响应。
编辑(给定从服务器返回的 JSON):
要设置序列化映射和对象映射并发布它,您需要设置资源路径(我在启动应用程序时会这样做):
RKObjectRouter *router = [RKObjectManager sharedManager].router;
[router routeClass:[User class] toResourcePath:@"/users" forMethod:RKRequestMethodPOST];
您的资源路径可能不是“/users”。
看一下注释下的代码//Then you set up a serialization mapping and object mapping and POST it
,我在其中添加了序列化映射、对象映射和 POST。