gpt4 book ai didi

ios - 如何解析nsstring中的json数据?

转载 作者:行者123 更新时间:2023-11-28 21:28:32 24 4
gpt4 key购买 nike

我正在收到这样的 API 响应。

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

但是当我尝试获取 token 的值时,它会同时为我提供 null,而当我获取 role 的值时,它会给我完美的值。

请看我的代码。

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

最佳答案

你需要这样做

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

关于ios - 如何解析nsstring中的json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37177814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com