如何从url中检索json数据

时间:2013-04-03 21:22:00

标签: iphone ios objective-c json

基本上我试图从自定义搜索引擎中检索json数据并且我没有成功(链接只是一个占位符不能显示真实链接)。我将发布我的目标c代码并将显示我的json代码底部。基本上我试图从中检索TermText,但我没有成功。我基本上从一个bing教程中删除了这个代码。任何帮助都会受到赞赏。现在,代码给我一个控制台日志nil。
.H

   @interface ViewController : UIViewController{
NSString *jsonstring;
    }
   @property (nonatomic,retain)NSString *offValue;
     -(void) searchBing:(NSString *)text;
     -(void)getData:(NSData *) response;

的.m

   -(void)searchBing:(NSString *)text{
//MODIFY
NSString *urlString=[NSString stringWithFormat:@"%@%@%@%@",@"http://api/text data.",text,@"&sources=web&web.offset=",offValue];
NSURL *url =[NSURL URLWithString:urlString];
NSData *data =[NSData dataWithContentsOfURL:url];
[self getData:data];
     }
    -(void)getData:(NSData *)response{
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
NSLog(@"%@",json);
   }

- (void)viewDidLoad
  {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

offValue =@"0";
[self searchBing:@"Term"];
   }

的Json

     {
    "ReturnValue": [
{
  "Term": {
    "TermID": 1,
    "TermText": "sample string 2",
    "Description": "sample string 3"
  }
},
{
  "Term": {
    "TermID": 1,
    "TermText": "sample string 2",
    "Description": "sample string 3"
  }
},
{
  "Term": {
    "TermID": 1,
    "TermText": "sample string 2",
    "Description": "sample string 3"
  }
}
   ],
  "ResultCode": 0,
  "ResultCodeName": 0,
  "ErrorMessage": "sample string 2"
     }

2 个答案:

答案 0 :(得分:-1)

在你的getData:方法中,你应该检查错误!= nil,这可能会告诉你什么是错的。

其次,kNilOptions不是该参数的有效选项,您应该使用NSJSONReadingMutableContainers或其他一个定义Here的选项。

第三,NSLog(@"%@", json)只会给你关于对象本身的模糊信息,而不是它的内容,你应该使用NSLog(@"%@", [json description])

答案 1 :(得分:-1)

JSON文件可能太大了。也许您应该尝试使用NSURLConnectionDelegate和NSURLConnectionDataDelegat协议来检索运行循环中的数据。试着读一下。 http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/

顺便说一句,我猜想异步检索数据是一种更好的做法