2012-07-27 84 views
2

更新谷歌搜索使用JSON

看來resultField的iOS是一個沒有價值的人。將研究這一點,但我仍然感謝任何意見。

原貼

我已經設置想出一個基本的iOS應用,只是使搜索請求的任務,然後顯示爲大學工作的結果。我試圖使用谷歌自定義搜索引擎,但永遠不能讓它在iPhone上運行,所以我不得不求助於貶低的谷歌網頁搜索API(講師可以這麼做)。

現在,我可以提出請求,並按照預期返回JSON數據,我現在必須解析這些數據。可悲的是我只有一個星期做這件事,這是瘋狂的,因爲我從來沒有使用過JSON。

我想要的是如果有人能夠幫助我在一個或兩個指針的基礎上脫身,甚至可以獲得對JSON數據的基本解析。

我環視了一下Stackoverflow,看到了一些可能有用的東西,例如所選答案here中的分解結構。

的人把這個在一起,這在代碼中所示,當有一定的道理對我說:

一個偉大的結構解釋

dictionary (top-level) 
    sethostname (array of dictionaries) 
     dictionary (array element) 
      msgs (string) 
      status (number) 
      statusmsg (string) 
      warns (array) 
       ??? (array element) 

可悲的是,我不能甚至開始做同樣的與我的應用程序中生成的代碼。它採用與此示例代碼類似的形式,由google提供 - 我不是Paris Hilton粉絲!

來自Google的示例代碼。

{"responseData": { 
"results": [ 
    { 
    "GsearchResultClass": "GwebSearch", 
    "unescapedUrl": "http://en.wikipedia.org/wiki/Paris_Hilton", 
    "url": "http://en.wikipedia.org/wiki/Paris_Hilton", 
    "visibleUrl": "en.wikipedia.org", 
    "cacheUrl": "http://www.google.com/search?q\u003dcache:TwrPfhd22hYJ:en.wikipedia.org", 
    "title": "\u003cb\u003eParis Hilton\u003c/b\u003e - Wikipedia, the free encyclopedia", 
    "titleNoFormatting": "Paris Hilton - Wikipedia, the free encyclopedia", 
    "content": "\[1\] In 2006, she released her debut album..." 
    }, 
    { 
    "GsearchResultClass": "GwebSearch", 
    "unescapedUrl": "http://www.imdb.com/name/nm0385296/", 
    "url": "http://www.imdb.com/name/nm0385296/", 
    "visibleUrl": "www.imdb.com", 
    "cacheUrl": "http://www.google.com/search?q\u003dcache:1i34KkqnsooJ:www.imdb.com", 
    "title": "\u003cb\u003eParis Hilton\u003c/b\u003e", 
    "titleNoFormatting": "Paris Hilton", 
    "content": "Self: Zoolander. Socialite \u003cb\u003eParis Hilton\u003c/b\u003e..." 
    }, 
    ... 
], 
"cursor": { 
    "pages": [ 
    { "start": "0", "label": 1 }, 
    { "start": "4", "label": 2 }, 
    { "start": "8", "label": 3 }, 
    { "start": "12","label": 4 } 
    ], 
    "estimatedResultCount": "59600000", 
    "currentPageIndex": 0, 
    "moreResultsUrl": "http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8..." 
} 
} 
, "responseDetails": null, "responseStatus": 200} 

這是到目前爲止的代碼,正如你就會很快學會並沒有真正做很多其他比類似於上面的代碼返回代碼。

**My code.** 


// query holds the search term 
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

//append theQuery with search URL 
NSString *tempString = [NSString stringWithFormat:@"%@/%@", @"https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=", theQuery]; 


//Create NSURL out of tempString 
NSURL *url = [NSURL URLWithString:tempString]; 


// Create a request object using the URL. 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

// Prepare for the response back from the server 
NSHTTPURLResponse *response = nil; 
NSError *error = nil; 

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 


    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&error]; 

    NSDictionary* resultField = [NSDictionary dictionaryWithDictionary:[dictionary objectForKey:@"results"]]; 

// Send a synchronous request to the server (i.e. sit and wait for the response) 

// Check if an error occurred 
if (error != nil) { 
    NSLog(@"%@", [error localizedDescription]); 
    // Do something to handle/advise user. 
} 

// Convert the response data to a string. 
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

    NSArray *results = [dictionary objectForKey:@"results"]; 
    //set label's text value to responseString's value. 
endLabel.text = responseString; 

現在我遇到的主要問題是結果數組始終爲空。我真的可以在這裏向正確的方向提出一個觀點。謝謝。

+0

您是否檢查了各種對象的值?我猜你的responseData正在填充正確,但然後是字典它應該是什麼? – 2012-07-27 21:40:38

+0

好點,謝謝。我檢查了不同變量的值,resultField是最後一個結果爲null的變量。這給了我一些工作,謝謝。 – 2012-07-27 23:41:59

回答

2

它看起來像遍歷從JSON解析出來的數據結構時遇到了問題。

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&error]; 

假設您傳入的數據很好,這個dictionary包含頂層結構。它有三個鍵responseDataresponseDetailsresponseStatus。 (您可以通過NSLog查看該字典。)

然後,您正在查詢該字典中的密鑰results。它不存在,所以你的resultField變量設置爲nildictionary的密鑰responseData的值是另一個包含密鑰的字典results - 您需要中間步驟。

另外,第二個字典中results鍵的值是一個數組(更多字典),而不是字典本身。

+0

太好了,謝謝。我現在可以顯示搜索結果的標題。我現在需要包含網址和結果詳細信息。所以結果NSArray包含多個字典 - 每個字典都是帶有自己標題,URL等的搜索結果? 此外,這段代碼是否正確? endLabel.text = [NSString stringWithFormat:@「Title:%@ URL%@」,[result objectForKey:@「title」],[(NSDictionary *)[result objectForKey:@「visibleURL」] objectForKey:@「url 「]]; 我剛剛從URL中獲取null。謝謝您的幫助。對於對此如此無知,我表示歉意,之前我從未與之合作過,也沒有很長時間。 – 2012-07-28 11:06:51

+0

嘗試僅記錄[result objectForKey:@「visibleURL」]。它是一本字典嗎? – rickster 2012-07-28 20:08:15

0

沒有必要每次創建一個新的字典。爲了更容易閱讀,我推薦如下:

[[dictionary objectForKey:@"responseData"] objectForKey:@"results"] 

在那裏你有一系列的結果。您可以添加

[ [dictionary objec...] objectAtIndex:0]