【发布时间】:2016-10-25 13:38:35
【问题描述】:
我知道有许多类似的 SO 问题与我的标题相似。我已经检查了它们,但仍然遇到这个问题。
我正在尝试访问一个 API,该 API 返回一个应该/可以被格式化为 JSON 的字符串。
要检索此字符串并将字符串转换为 JSON,我正在使用(未成功)此代码:
NSError *error;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@",responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(@"%@",[json objectForKey:@"ID"]);
NSLog(@"Json: %@",json);
}];
[task resume];
NSLog(@"Response:...) 返回一个字符串,当我将其输入本网站时:http://jsonviewer.stack.hu 确认该字符串是有效的 JSON。
两个应该返回 JSON 值的 NSLog 返回 null。
我尝试了什么:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData 选项:NSJSONReadingMutableContainers 错误:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data 选项:NSJSONReadingMutableContainers 错误:&error];
我现在也试过了:
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonObject;
NSError *err = nil;
@try
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}
@catch (NSException *exception)
{
NSLog( @"Exception caught %@",exception);
}
NSDictionary *info = jsonObject;
NSLog(@"Json: %@",info);
}];
[task resume];
我在这里做错了什么?如何获得 NSDictionary (JSON) 结果。
【问题讨论】:
-
你在 responseString 中得到了什么?
-
你的 JSON 真的是顶级的 NSDictionary 吗?使用
error参数怎么样? -
将
NSData转换为NSString并直接转换回NSData非常愚蠢。根据您的代码data和jsonData是相同的 -
@vadian 知道这一点,但想看看字符串的输出是什么。
-
但无论如何,将其转换回来的额外步骤是多余的。您确定 JSON 的根对象是字典吗?并处理错误。
标签: objective-c json nsurlsession