iphone - 如何从url中获取json数据

标签 iphone ios objective-c json

基本上,我正在尝试从自定义搜索引擎检索 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/

相关文章:

iOS 应用内购买错误 - 此项目不再可用

iphone - 在CGMutablePath中绘制UIImage

ios - 此版本的 Xcode 不支持 IOS 文档的自动布局

iphone - iPhone应用程序生命周期中的最后一个功能是什么

ios - 重置 Facebook token 引用 - Facebook SDK 4.0

iphone - 显示带有视频和链接的 PDF

iphone - 在不更改任何代码的情况下将 iPhone 应用程序提交为通用是否有效?

iphone - 标签栏和导航 Controller 内的 MKMapView 隐藏了 Google 品牌

ios - 颜色色调 UIButton 图像

objective-c - 如何对当天添加的实体发出提取请求?