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 t
In iOS 5.1+ there's NSJSONSerialization.
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) {
}];
You could use an open source library like JSONKit for that. It is able to parse a JSON response into a NSDictionary or NSArray.
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;
}