问题
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.
Here is my code
- (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];
}
How can I get the JSON data to a readable object? Thanks
回答1:
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;
}
回答2:
In iOS 5.1+ there's NSJSONSerialization.
回答3:
Here is an example using RestKit 0.2 and NSJSONSerialization:
[[RKObjectManager sharedManager] getObjectsAtPath:kLoginURL
parameters:params
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSError *error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:operation.HTTPRequestOperation.responseData options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"msg: %@", [json objectForKey:@"msg"]);
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
回答4:
You could use an open source library like JSONKit for that. It is able to parse a JSON response into a NSDictionary or NSArray.
来源:https://stackoverflow.com/questions/12054334/parsing-json-without-object-mapping-in-restkit-ios