-1

How do I extract just the "token" value from the following code? I'm looking to save this value into a string.

Is meta an array? If so how would I extract the data from the "token" value?

thanks for any help

 NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];


Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
    data =     {
        token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
    };
    meta =     (
    );
}
hanumanDev
  • 6,592
  • 11
  • 82
  • 146

3 Answers3

2

I believe the data is in JSON format. In that case, this should work.

NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:@"data"] objectForKey:@"token"];
Ahmed Mohammed
  • 1,134
  • 8
  • 10
1

In your Case, meta is an Array and data is a Dictionary. If your Response is properly formatted in JSON then you can use the below sample code to get the TokenString and metaArray.

Sample Code :

NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:@"data"] objectForKey:@"token"];
NSArray *meta = [responseDict objectForKey:@"meta"];
NSLog(@"\ntoken :: %@\nmeta :: %@",token,meta);

PS : To know more about JSON response , take a look at this Answer.

Community
  • 1
  • 1
Bhavin
  • 27,155
  • 11
  • 55
  • 94
1

I'd just do this:

NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
  options:kNilOptions error:NULL][@"data"][@"token"];

It will be nil if there's any error.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110