0
- 我有一個QR碼圖像。我在iOS中掃描該圖像並獲取一個網址。
- 我通過JSON對象將該URL發佈到webservice,並返回一個「ProjectID」。
- 如果該項目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!");
}
}];
請格式化你的代碼是什麼錯誤返回,當你調用'JSONObjectWithData'? – Wain