基本上,我正在尝试从自定义搜索引擎检索 json 数据,但没有成功(链接只是一个占位符,无法显示真实链接)。我将发布我的 objective-c 代码,并在底部。基本上我试图从中检索 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"
}
最佳答案
在您的 getData:
方法中,您应该检查 error != nil 是否存在,这可能会告诉您哪里出了问题。
其次,kNilOptions
不是该参数的有效选项,您应该使用 NSJSONReadingMutableContainers
,或定义的其他选项之一 Here .
第三,NSLog(@"%@", json)
只会给你关于对象本身的模糊信息,而不是它的内容,你应该使用 NSLog(@"%@ ", [json 描述])
.
关于iphone - 如何从url中获取json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798384/