sandeep tomar sandeep tomar - 5 months ago 21
iOS Question

How to parse json data in nsstring?

I am getting response form api like this.

{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG4uc21pdGhAZ21haWwuY29tIiwiaWQiOiI1NzFkYzI3NmU0YjA1NjVmNTcwZjM2ZGQiLCJpYXQiOjE0NjMwMjk4NDd9.yi8H75GTS-U8abcS75WcGT5ROfmM0AgCNfRIiZQzeNI","data":{"name":"John Smith","role":"driver"},"message":"success"}


But when I try to get value of token it gives me null at the same time when get value of role it give me perfect value.

Please look at my code.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://qa.networc.in:1336/api/drivers/login"]];
NSURLSession *session = [NSURLSession sharedSession];

NSString * params =[NSString stringWithFormat:@"email=%@&password=%@&deviceId=fc2ffdf08ccf0dc912018f7232e4aa0ffcbd856ec3faf4145649f8bb281a779d",_driverNumberTextField.text,_passwordTextField.text];
NSLog(@"params %@", params);

request.HTTPMethod = @"POST";
request.HTTPBody =[params dataUsingEncoding:NSUTF8StringEncoding];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
// use NSJSON Serlizeitaion and serlize your value
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);

id object = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"JSON"];
NSString *temp;
temp = (NSString*)[dictionary valueForKey:@"token"];
NSLog(@"temp %@", temp);

dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];
Role = (NSString*)[dictionary valueForKey:@"role"];
NSLog(@"role %@", Role);

Answer

you need to do like

dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
     NSString *temp =  (NSString*)[dictionary valueForKey:@"token"];
      NSLog(@"temp %@", temp);

NSDictionary *data = [dictionary valueForKey:@"data"];
  NSString *tnamemp = (NSString*)[data valueForKey:@"name"];
    NSString *role = (NSString*)[data valueForKey:@"role"];