发布json之后的RestKit,如何映射json对象的响应

时间:2012-07-04 00:34:53

标签: restkit

我按照此链接https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON创建json帖子,并从服务器获取json响应。我怎样才能继续处理对象列表的json响应?

- (void)sendAsJSON:(NSDictionary*)dictionary {

    RKClient *client = [RKClient clientWithBaseURL:@"http://restkit.org"];        

    // create a JSON string from your NSDictionary 
    id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
    NSError *error = nil;
    NSString *json = [parser stringFromObject:dictionary error:&error];

    // send your data
    if (!error)
        [[RKClient sharedClient] post:@"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];

}


- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response
{
    NSLog(@"after posting to server, %@", [response bodyAsString]);
}

EDIT1:这是我想要POST到服务器的Json。

{
    "memberId": "1000000",
    "countryCode": "US",
    "contacts": [
        {
            "phoneNumber": "+12233333333",
            "memberId": "2222",
            "contactId": "123456",
            "name": "john"
        },
        {
            "phoneNumber": "+12244444444",
            "memberId": "3333",
            "contactId": "123457",
            "name": "mary"
        }
    ]
}

EDIT2:有人在另一个帖子中解决了这个问题。 https://stackoverflow.com/a/7726829/772481

2 个答案:

答案 0 :(得分:4)

使用RKObjectManger而不是RKClient来执行POST。然后,您可以在调用此方法时将响应加载到对象中:

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects

编辑(给定JSON发送到服务器):

您可以创建自定义模型类,而不是按照当前的方式创建JSON。

首先,您可以为顶级对象创建一个模型类(假设它叫做User)。

用户标题

//  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)

要设置序列化映射和对象映射并对其进行POST,您需要设置资源路径(我在启动应用程序时执行此操作):

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。

答案 1 :(得分:0)

通常在这种情况下,您可以使用RKObjectLoader,可以通过RKObjectManager访问,如@ill_always_be_a_warriors所述。您使用它的原因是因为它包括自由对象映射(如果已配置)。需要注意的一件事是你发布了一个'对象'而不是直接发布JSON。有关详细信息,请尝试查看RestKit examples以查看如何执行此操作,如果您在此处发布问题时仍有问题。