如何解析nsstring中的json数据?

时间:2016-05-12 05:14:22

标签: ios objective-c json

我正在接受这样的api回复。

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

但是当我试图获得令牌的价值时,它在获得角色价值的同时给予我null,它给了我完美的价值。

请查看我的代码。

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);

6 个答案:

答案 0 :(得分:1)

NSJSONSerialization会返回字典,因此您无需执行objectForKey:@"JSON"

替换

dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"JSON"];

dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

建议:不要再次解析字典只是为了从同一个字典中检索不同的密钥。使用相同的字典。

NSString *token = dictionary[@"token"];
NSString *role  = dictionary[@"data"][@"role"];
NSString *name  = dictionary[@"data"][@"name"];

答案 1 :(得分:1)

//我希望它适用于你

  NSMutableDictionary *dic= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  NSString *strToke = [dic valueForKey:@"token"];

答案 2 :(得分:1)

你需要做的事情

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"];

答案 3 :(得分:0)

请尝试以下代码: 问题出在这里:

dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"JSON"];

试试下面的代码。希望这有帮助!

NSError *error = nil;
    NSDictionary *responseObj = [NSJSONSerialization
                                 JSONObjectWithData:jsonData
                                 options:0
                                 error:&error];

if(! error) {
    NSLog(@"responseObj : %@",responseObj);
    NSString *token = [responseObj valueForKey:@"token"];
    NSDictionary *dataDic = [responseObj valueForKey:@"data"];
    NSString *role = [dataDic valueForKey:@"role"];
    NSString *name = [dataDic valueForKey:@"name"];


} else {
    NSLog(@"Error in parsing JSON");
}

答案 4 :(得分:0)

获取密钥存在问题 试试这个,

     NSDictionary  *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
     NSString *strToken =  (NSString*)[dataDictionary valueForKey:@"token"];
     NSLog(@"Token %@", strToken);

     NSString *strName = (NSString*)[[dataDictionary valueForKey:@"data"] valueForKey:@"name"];
     NSString *strRole = (NSString*)[[dataDictionary valueForKey:@"data"] valueForKey:@"role"];

答案 5 :(得分:-1)

打印单个值并检查。访问阵列$arr["token"]