使用JSON的iOS谷歌搜索

使用JSON的iOS谷歌搜索,ios,json,nsdictionary,Ios,Json,Nsdictionary,更新 似乎resultField是一个没有值的字段。我会调查的,但我还是很感激你的建议 原创帖子 我的任务是开发一个基本的iOS应用程序,它只需发出一个搜索请求,然后显示大学工作的结果。我曾尝试使用谷歌定制搜索引擎,但无法在iPhone上运行,因此我不得不求助于降价的谷歌网络搜索API(讲师对此没有意见) 现在,我可以发出请求,它会按预期返回JSON数据,我想现在必须解析它。遗憾的是,我只有一周的时间来做这件事,这太疯狂了,因为我以前从未使用过JSON 我想知道的是,如果有人能帮我用一两个指针就

更新

似乎resultField是一个没有值的字段。我会调查的,但我还是很感激你的建议

原创帖子

我的任务是开发一个基本的iOS应用程序,它只需发出一个搜索请求,然后显示大学工作的结果。我曾尝试使用谷歌定制搜索引擎,但无法在iPhone上运行,因此我不得不求助于降价的谷歌网络搜索API(讲师对此没有意见)

现在,我可以发出请求,它会按预期返回JSON数据,我想现在必须解析它。遗憾的是,我只有一周的时间来做这件事,这太疯狂了,因为我以前从未使用过JSON

我想知道的是,如果有人能帮我用一两个指针就如何获得JSON数据的基本解析。

{"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}
我环顾了Stackoverflow,看到了一些可能有用的东西,比如所选答案中的分解结构

这个人把这些放在一起,当代码中显示出来时,我觉得有点道理:

很好的结构解释

dictionary (top-level)
     sethostname (array of dictionaries)
         dictionary (array element)
            msgs (string)
            status (number)
            statusmsg (string)
            warns (array)
                ??? (array element)
遗憾的是,我甚至不能对我的应用程序中生成的代码进行同样的处理。它的形式类似于这个示例代码,这是出于-我不是帕里斯·希尔顿的粉丝

来自谷歌的示例代码。

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

现在我遇到的主要问题是results数组始终为null。我真的需要一个指向正确方向的点。谢谢。

看起来您在遍历从JSON解析出来的数据结构时遇到了问题

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&error];
假设传入的数据良好,则此
字典包含顶级结构。它有三个键
responseData
responseDetails
,和
responseStatus
。(您可以通过
NSLog
查看字典来了解这一点。)

然后,您将在该词典中查询键
结果
。它不存在,因此您的
resultField
变量设置为
nil
。键
响应数据的
字典
值是另一个包含键
结果的字典--
--您需要中间步骤


另外,第二个字典中的
results
键的值是一个数组(多个字典),而不是字典本身

没有必要每次都创建一个新词典。为了便于阅读,我推荐如下内容:

[[dictionary objectForKey:@"responseData"] objectForKey:@"results"]
这就是结果数组。然后您可以添加

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

您是否检查过各种对象的值?我猜您的responseData填充正确,但字典应该是什么?很好,谢谢。我已经检查了不同变量的值,resultField是一个以null结尾的变量。这给了我一些工作,谢谢。太好了,谢谢。我现在可以显示搜索结果的标题。我现在需要包括URL和结果详细信息。所以结果NSArray包含多个字典-每个字典都是一个有自己标题、URL等的搜索结果?还有,这个代码正确吗?endLabel.text=[NSString stringWithFormat:@“Title:%@URL%@”,[result objectForKey:@“Title”],[(NSDictionary*)[result objectForKey:@“visibleURL”]objectForKey:@“URL”];我只是从URL中得到null。谢谢你的帮助。很抱歉我对这一点一无所知,我以前从未使用过它,也没有很长时间可以使用它。请尝试只记录[result objectForKey:@“visibleURL]”。它是一本字典吗?