2013-08-20 35 views
0
  1. 我有一个QR码图像。我在iOS中扫描该图像并获取一个网址。
  2. 我通过JSON对象将该URL发布到webservice,并返回一个“ProjectID”。
  3. 如果该项目ID有一个正值,我应该返回YES指示扫描的URL对web服务有效,否则返回NO。

[出于测试目的,我已对硬编码的URL返回YES。我将在稍后获取扫描的URL]iOS:如何提取JSON对象中某个键的值

如何提取项目ID我记录并检查条件。

这里是我的编码

NSError *error; 

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"[email protected]" ,@"EmailID", @"http://www.yahoo.com", @"URL", @"", @"Phone", @"", @"UserID", nil]; 


    NSURL *url = [NSURL URLWithString:@"http:// some url"]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 

NSData *requestData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error]; 

     [request setHTTPMethod:@"POST"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
     [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"]; 
     [request setHTTPBody: requestData]; 
     [request setTimeoutInterval:180]; 

     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
     [connection start]; 
     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ 
     if(error || !data) 
     { 
      NSLog(@"JSON NOT posted"); 
     } 
     else 
     { 
      id jsonObject = [NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingAllowFragments error:Nil]; 

      if([jsonObject respondsToSelector:@selector(objectForKey:)]) 
      { 
       NSDictionary *dictionaryForUserID = [jsonObject valueForKey:@"ProjID"]; 
       NSLog(@" Project Id = %@", dictionaryForUserID); 

    /* I get "Project ID = (null)" here whereas I get one positive value in the log. My question is how to get the projectID in log? */ 

    /* log output :: 

    2013-08-20 11:57:34.765 appname[585:5903] Project Id = (null) 

    2013-08-20 11:57:34.766 appname[585:5903] JSON data posted! 

    2013-08-20 11:57:34.769 appname[585:c07] Data: 
    {"ProjID":"5","ProjName":null,"URL":null,"EmailID":null,"Phone":null,"userId":null}{"ProjID":"5","ProjName":null,"URL":null,"EmailID":null,"Phone":null,"userId":null} 

    */ 

      } 
      NSLog(@"JSON data posted!"); 
     } 
    }]; 
+0

请格式化你的代码是什么错误返回,当你调用'JSONObjectWithData'? – Wain

回答

2

嗯,问题是你解析你的请求数据而不是响应数据。

试试这个:

id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:Nil]; 
1

看看你的代码的密切关注。您正在解析从服务器收到的requestData,而不是data。祝你好运!