xzrudy xzrudy - 3 months ago 13
iOS Question

Parsing JSON Within JSON in Objective-C

I'm trying to store the JSON that is within the JSON i get from the following request...

NSURL *URL = [NSURL URLWithString:@"http://www.demo.com/server/rest/login?username=admin&password=123"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
^(NSData *data, NSURLResponse *response, NSError *error) {

if (error) {
// Handle error...

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);

NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response Body:\n%@\n", body);
[task resume];

The resulting JSON obtain from body is the following and as you can see there is a JSON within the JSON, how can I store that JSON in a NSDictionary as you can see that JSON is between quotation marks.

tag: "login",
status: true,


What you have in reality: Classic JSON, where inside there is a String "representing" a JSON.

So, since we can do:
NSData <=> NSString
NSArray/NSDictionary <=> JSON NSData
We just have to switch between them according to the kind of data we have.

NSArray *topLevelJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
NSString *lowLevelString = [[topLevelJSON firstObject] objectForKey:@"data"]; 
NSData *lowLevelData = [lowLevelString dataUsingEncoding:NSUTF8StringEncoding]; 
NSDictionary *final = [NSJSONSerialization JSONObjectWithData:lowLevelData options:0 error:nil];