在Restkit iOS中解析没有对象映射的JSON [英] Parsing JSON without Object Mapping in Restkit iOS
问题描述
我创建了一个登录页面,它使用Restkit RKClient
来发送登录详细信息,并获取JSON数据(用户或错误)。我希望能够在没有对象映射的情况下解析JSON数据,只需要JSON到字典。原因是它只是一个简单的登录发送用户名和密码,如果我设置对象映射,我将必须将登录详细信息设置为Login对象,然后设置路由等...它似乎是一个有点啰嗦。
I've created a login page which uses Restkit RKClient
to send login details, and get back JSON data (either the user or an error). I want to be able to parse the JSON data without object mapping, just JSON to dictionary. The reason for this is it's just a simple login thats sending username and password, if I set up object mapping, i'll have to set up the login details into a Login object, then set up routing etc... and it seem a bit long winded.
这是我的代码
- (IBAction)login:(id)sender
{
[self.activityIndicator startAnimating];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObject:self.username.text forKey:@"username"];
[params setObject:self.password.text forKey:@"password"];
[params setObject:@"login" forKey:@"type"];
[[RKClient sharedClient] post:@"/login" params:params delegate:self];
}
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
if ([request isPOST]) {
if ([response isJSON]) {
NSLog(@"Got a JSON response back from our POST: %@", response.bodyAsString);
}
}
[self.activityIndicator stopAnimating];
}
如何将JSON数据提供给可读对象?谢谢
How can I get the JSON data to a readable object? Thanks
推荐答案
您只需在RKResponse对象上调用parsedBody:nil并将返回的对象分配给NSDictionary:
You can simply call parsedBody:nil on your RKResponse object and assign the returned object to an NSDictionary:
responseDict = [response parsedBody:nil];
作为额外检查,我使用一点便利方法来检查响应是否成功:
And as an extra check I use a little convenience method to check for a a successful response:
- (bool) wasRequestSuccessfulWithResponse:(RKResponse*)response {
bool isSuccessfulResponse = NO;
id parsedResponse;
NSDictionary *responseDict;
if(response != nil) {
parsedResponse = [response parsedBody:nil];
if ([parsedResponse isKindOfClass:[NSDictionary class]]) {
responseDict = [response parsedBody:nil];
if([[responseDict objectForKey:@"success"] boolValue]) {
isSuccessfulResponse = YES;
}
}
}
return isSuccessfulResponse;
}
这篇关于在Restkit iOS中解析没有对象映射的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!