2013-08-20 62 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。祝你好運!