Working in java, not in objective c. Data is not saved in the database despite getting in "Json Data Posted" condition.
I should send the data in the format as shown below to get the json response
{
"ProjID": "78",
"Uid": "12",
"EmailID": "ratnam_nv#yahoo.com",
"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"
}
]
};
I am sending the dictionary I got in log in the format as shown below.
The differnce between the above code and my log's screenshot is ';' after every key value pair and hence I get the response as mentioned in the title.
Any suggestions to correct the code/logic? Here's what I coded.
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", #"ratnam_nv#yahoo.com", #"EmailID", arrayAnswer, #"ProjectInviterFQAnswer", nil];
NSLog(#"Dictionary that is being sent to URL is = %#", dictionary);
NSURL *url = [NSURL URLWithString:#"http://cnapi.iconnectgroup.com/api/QRCodeScan/SaveAnswers"];
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);
[activity stopAnimating];
}
}];
}
So here's how I solved my own issue.
NSString *str = #"{\"ProjID\": \"78\",\"Uid\": \"12\",\"EmailID\": \"ratnam_nv#yahoo.com\",";
str = [str stringByAppendingString:#"\"ProjectInviterFQAnswers\": ["];
str = [str stringByAppendingString:#"{\"slno\": \"1\",\"Answer\": \"a1\",\"order\": \"1\", \"flag\": \"F\"},"];
str = [str stringByAppendingString:#"{\"slno\": \"2\",\"Answer\": \"a1\",\"order\": \"1\",\"flag\": \"F\"},"];
str = [str stringByAppendingString:#"{\"slno\": \"1\",\"Answer\": \"a1\",\"order\": \"2\",\"flag\": \"Q\"}"];
str = [str stringByAppendingString:#"]}"];
NSLog(#"String is === %#", str);
NSURL *url = [NSURL URLWithString:#"http://cnapi.iconnectgroup.com/api/QRCodeScan/SaveAnswers/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
[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);
}
}];
In my case I got the same error, the issue was that I send the wrong data to the service. Basically, the error was caused by setting the wrong body with the line:
[request setHTTPBody: requestData];
Between, sendSynchronousRequest is deprecated in iOS9. Use
...
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
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);
[activity stopAnimating];
}
}] resume];
Related
NSError *error;
NSDictionary *dicData = [[NSDictionary alloc]initWithObjectsAndKeys:username,#"username",password,#"password",cpassword,#"cpassword",mobile,#"mobile",firstname,#"firstname",lastname,#"lastname",#"register",#"action",nil];
NSLog(#"parameter=%#",dicData);
NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in dicData) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
}
components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:components.URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#",data);
NSLog(#"%#",response);
NSLog(#"%#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
dispatch_async(dispatch_get_main_queue(), ^
{
if (error !=nil) {
NSLog(#"%#",error.description);
NSLog(#"%#",error.localizedDescription);
}
else {
completion(dicResult);
}
});
}];
[task resume];
}
In order send request for getting data, you have to add key in info.plist as follow :
And just update your code as below :
NSError *error;
NSDictionary *dicData = [[NSDictionary alloc] initWithObjectsAndKeys:#"user123", #"username", #"pass1234", #"password", #"pass1234", #"cpassword", #"0123456789", #"mobile", #"User", #"firstname", #"Name", #"lastname", #"register", #"action", nil];
NSLog(#"parameter=%#",dicData);
// NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
//
// NSMutableArray *queryItems = [NSMutableArray array];
// for (NSString *key in dicData) {
// [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
// }
// components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://followerlikes.com/app_appoint/json/?action=register"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Data : %#",data);
NSLog(#"RESPONSE : %#",response);
NSLog(#"ERROR : %#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
NSLog(#"RESPONSE DICT : %#", dicResult);
dispatch_async(dispatch_get_main_queue(), ^ {
if (error !=nil) {
NSLog(#"ERROR : %#",error.description);
NSLog(#"ERROR : %#",error.localizedDescription);
}
else {
// completion(dicResult);
}
});
}];
[task resume];
I am trying to get connection from server and receive response from server but I can't understand for the response code.
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#",#"_username",#"_password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://<MY_URL>"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
this is correct or not because I am not getting a response .??
now what is code for response?????
NSURLResponse *response=nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(#"%#",response);
if (response) {
//UIStoryboard *story=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
//TableViewController *obj=[story instantiateViewControllerWithIdentifier:#"table1"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login success" message:#"correct Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
//[self.navigationController pushViewController:obj animated:YES];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login Failure" message:#"Incorrect Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
}
You need to fetch that data:
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseData) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
NSLog(#"res---%#", results);
}
and use dictionary for further use.
ALL the code is correct only you need to add the this in your info.plist
App Transport Security Setting
Allow arbitrary Loads
I'm using this piece of code for hit data in url.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
value of uitextfield is not store in url when i clicked on button, what should i do here?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
//_Email.text,#"email_id", _Password.text,#"password",nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"yyyyy",#"company_name",
#"karthik.saral#gmail.com",#"email_id", #"XXXXX",#"password",nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
NSLog(#"answewrv : %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
this is updated code after the amendments. i am getting the same error.
You are wrong here:
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
It should be
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
_Email.text,#"email_id", _Password.text,#"password",nil];
initWithObjectsAndKeys mean: object,key, object, key
I have done also this type work you can see this , may be it will help you.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#" your URL "];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=%#&password=%#&api_key=Your key", usernameField.text,passwordField.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"%#", mapData);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self presentViewController:i animated:YES completion:Nil];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
I want to post Dictionary to a Web service. but it is not getting post .Every time when i post data i am getting error message form web-service. I also try different approach using AFNetworking but using that approach i am getting 406 error.
you can see the other question here
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.txtUserName.text forKey:#"name"];
[params setValue:self.txtEmail.text forKey:#"mail"];
[params setValue:self.txtPass.text forKey:#"conf_mail"];
[params setValue:self.txtPass2.text forKey:#"pass"];
NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError){
NSLog(#"Error: %#", connectionError);
[ProgressHUD dismiss];
}
else {
NSLog(#"data as String: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:&e];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSMutableDictionary *dict1=[dict objectForKey:#"data"];
NSLog(#"data -- %#",[dict objectForKey:#"data"]);
NSLog(#"status -- %#",[dict objectForKey:#"status"]);
int num=[[dict valueForKey:#"status"]intValue];
if( num== 0)
{
NSString *strMail=[dict1 valueForKey:#"mail"];
NSString *strName=[dict1 valueForKey:#"name"];
NSString *strPass=[dict1 valueForKey:#"pass"];
if(strMail.length==0)
{
strMail=#"";
}
if(strName.length==0)
{
strName=#"";
}
if(strPass.length==0)
{
strPass=#"";
}
NSString *Message=[NSString stringWithFormat:#"Please correct the follwing \n %# \n %#\n %# ",strMail,strName,strPass];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:Message delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:#"%#",[dict1 objectForKey:#"message"]] delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
}
[ProgressHUD dismiss];
}
}];
The body you posted generated by NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params]; is NSPropertyListBinaryFormat_v1_0 which is a binary serialize data.
Http server could not recognise it. You can POST by JSON
NSData *body = [NSJSONSerialization dataWithJSONObject:"NSDictionary variable name"
options:NSJSONWritingPrettyPrinted
error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
How to get the following response from a "post" webservice.
I have an array of strings called textArray.
How to post that textArray for the key #"Answer" in the following response.
{
"ProjID": "78",
"Uid": "12",
"EmailID": "ratnam_nv#yahoo.com",
"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"
}
]
};
Here's what I tried so far
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", #"ratnam_nv#yahoo.com", #"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];
}
}];
Please be careful:
NSArray *keys = [NSArray arrayWithObjects:#"slno", #"Answer", #"order", #"flage", nil];
but you have:
"flag": "Q"
flage != flag.
That's why it is good to use constants!
Next, regarding you question:
First you have to transform the JSON into a NSDictionary.
After:
NSArray * array = [jsonDict valueForKey:#"ProjectInviterFQAnswer"];
for(NSMutableDictionary * dict in array){
[dict setValue:<put here anything you want> forKey:#""];
}
after you do that, create a new JSON from jsonDict, and you're done.
First of all you have to convert the response into dictionary and the set the value of answer your textArray String and then again convert it into json string