- 如何从“发布”web服务获取以下响应。
我有一个名为textArray的字符串数组。 如何在以下响应中为键@“答案”发布textArray。iOS:将字符串数组发布到以下JSON的Web服务
{ "ProjID": "78", "Uid": "12", "EmailID": "[email protected]", "ProjectInviterFQAnswers": [{ "slno": "1", "Answer": "a1", "order": "1", "flag": "F" }, { "slno": "2", "Answer": "a1", "order": "2", "flag": "F" }, { "slno": "1", "Answer": "a1", "order": "2", "flag": "Q" } ] };
这里是我试过到目前为止
NSError *error = Nil;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *dictionaryArray1 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"slno", @"a1", @"Answer", @"1", @"order", @"F", @"Flag", nil];
NSDictionary *dictionaryArray2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2", @"slno", @"a1", @"Answer", @"1", @"order", @"F", @"Flag", nil];
NSDictionary *dictionaryArray3 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"slno", @"a1", @"Answer", @"2", @"order", @"Q", @"Flag", nil];
NSArray *arrayAnswer = [NSArray arrayWithObjects:dictionaryArray1, dictionaryArray2, dictionaryArray3, nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"78", @"ProjID", @"12", @"UID", @"[email protected]", @"EmailID", arrayAnswer, @"ProjectInviterFQAnswer", nil];
NSURL *url = [NSURL URLWithString:@" someurl "];
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];
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 Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Data not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(@"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Response is %@", jsonObject); //Not getting the response here Message = "An error has occurred."
[activity stopAnimating];
}
}];
你试过了什么?你面临什么问题?如果你没有尝试过自己而不是第一次尝试,而是比较具体的问题。 – CRDave
使用NSDictionary或NSMutableDictionary创建键/值对。 祝你好运! –
@CRDave请参阅我的编辑 –