Ios 使用NSJSONSerialization时从NSDictionary获取null
我是新来的开发人员,请帮助我。我正在尝试做一个简单的应用程序,其中YQL链接用于获取本地数据并以表格格式显示。为此,我正在将数据转换为字典,稍后我想将其发送到表中。但当我试图将数据转换为字典时,它显示为null。请帮帮我。查看下面的屏幕截图。提前谢谢Ios 使用NSJSONSerialization时从NSDictionary获取null,ios,objective-c,json,yahoo-api,nsjsonserialization,Ios,Objective C,Json,Yahoo Api,Nsjsonserialization,我是新来的开发人员,请帮助我。我正在尝试做一个简单的应用程序,其中YQL链接用于获取本地数据并以表格格式显示。为此,我正在将数据转换为字典,稍后我想将其发送到表中。但当我试图将数据转换为字典时,它显示为null。请帮帮我。查看下面的屏幕截图。提前谢谢 NSString *str = @"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and
NSString *str = @"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
这里,我将json查询转换为字符串(*str)
当我试图实现这个注释代码时,我得到了预期的结果,但是我想把所有的数据放进字典并显示出来,所以我尝试将数据转换成字典
NSDictionary *dataFromWeb = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSDictionary *queryDict = [dataFromWeb objectForKey:@"query"];
NSDictionary *results = [dataFromWeb objectForKey:@"results"];
NSString *allResults = [queryDict objectForKey:@"Results"];
NSLog(@"%@", dataFromWeb);
}
默认情况下,从Yahoo API返回的响应是
XML
。您应该附加到querystring,以便以JSON
格式获取响应,以便可以使用NSJSONSerialization
类对其进行解析:
https://query.yahooapis.com/v1/public/yql?format=json&q=select...
Api返回xml数据,因此需要进行xml解析 NSJSONSerialization用于json解析
NSString *str = @"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
NSURL *UrlFromStr = [NSURL URLWithString:str];
在浏览器上点击此UrlFromStr,您会看到它返回的是xml数据,而不是json
使用NSXMLParser解析xml数据请使用NSXMLParser解析xml数据,而不是NSJSONSerialization。 NSJSONSerialization用于解析JSON数据 在.h文件中声明
@property (nonatomic, strong) NSXMLParser *xmlParser;
在.m文件中
NSString *str = @"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
self.xmlParser = [[NSXMLParser alloc] initWithData:data];
self.xmlParser.delegate = self;
// Initialize the mutable string that we'll use during parsing.
self.foundValue = [[NSMutableString alloc] init];
// Start parsing.
[self.xmlParser parse];
您要解析的对象的格式是XML,但您使用ParseJSON类来解析它,因此它返回NULL。您可以使用NSXML类来解析它,然后设置其委托以执行相关方法…祝您好运。您的Api不是json,它的XML格式使用XML解析器,请访问下面的链接
希望有帮助。使用
错误
参数。这是有原因的。
NSString *str = @"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
self.xmlParser = [[NSXMLParser alloc] initWithData:data];
self.xmlParser.delegate = self;
// Initialize the mutable string that we'll use during parsing.
self.foundValue = [[NSMutableString alloc] init];
// Start parsing.
[self.xmlParser parse];