簡體   English   中英

使用NSJSONSerialization時從NSDictionary獲取null

[英]Getting null from NSDictionary when NSJSONSerialization is being used

我是開發和stackoverflow的新手,請幫助我。 我正在嘗試做一個簡單的應用程序,其中YQL鏈接用於獲取本地數據並以表格格式顯示它。 為此我將數據轉換為字典,稍后我想將其發送到表中。 但是當我試圖將數據轉換為Dictionary時,它表示null。 請幫我。 檢查下面的截圖。 提前致謝。

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)

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]]; 

//   NSString *stringFromData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    NSLog(@"%@", stringFromData);

當我試圖實現這個注釋的代碼我得到了預期的結果,但我想把所有數據放入字典並顯示它,所以我試圖將數據轉換為字典

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 您應該將format=json附加到查詢字符串,以便以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 Parser,請訪問下面的鏈接,

http://www.theappguruz.com/blog/xmlparsing-with-nsxmlparser-tutorial

希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM