0

I am new to json, I want to pass the NSArray inside the NSDictionary as a parameter along with the url to server, how it can be done while method is post ? I had tried sample codes but not found my exact solution.below is my sample code

     NSDictionary *dict = [[NSDictionary alloc]   initWithObjectsAndKeys:@"contact_name", @"kumar",@"designantion",@"sales", nil];
    NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, @"OfficeContactPerson", nil];



    NSString *post =[[NSString alloc]initWithFormat:@"name=%@&short_name=%@&shop_no=%@&door_no=%@&floor=%@&building=%@&street=%@&area=%@&main=%@&city=%@&state=%@&district=%@&pincode=%@&telephone=%@&contact_name=%@&designatio=%@&mobile=%@&email=%@&OfficeContactPerson=%@",self.txtshowroom.text,self.txtshortname.text,self.txtshop.text,self.txtdoor.text,self.txtfloor.text,self.txtbuilding.text,self.txtstreet.text,self.txtarea.text,self.txtmain.text,cityineger,stateintegervalue,districtintegervalue,self.txtpincode.text,self.txttel.text,self.txtname.text,self.txtdesign.text,self.txtmbl.text,self.txtemail.text,finalDict];

    NSLog(@"postdata :%@",post);


    NSURL *url=[NSURL URLWithString:@"http://139.59.252.34:1337/office"];
    NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postlength=[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];

    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postlength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error=[[NSError alloc]init];
    NSHTTPURLResponse *response=nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


if (!urlData){


    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Error"message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
                                                   delegate:nil
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil];
    [alert show];

}
else
{
    NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"Response data ----->%@",responseData);
    NSError *error=nil;
    NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];

);
}



 OfficeContactPerson": [
  {
    "office": 29,
    "contact_name": "Priya",
    "designation": "Prop",
    "department": "ALL",
    "mobile": "1231231231",
    "email": "[email protected]",
    "incharge_status": null,
    "created_by": null,
    "modified_by": null,
    "id": 14,
    "createdAt": "2016-04-19T13:43:59.000Z",
    "updatedAt": "2016-04-19T14:25:36.000Z"
  }
]
1
  • 2
    convert array into Json string and send that string value over server Commented Apr 20, 2016 at 6:17

3 Answers 3

1

Convert array into json string or make dictionary of post data than convert it into json string and post string to server. I hope below code will work for you. This code is works fine for me-

NSDictionary *dict = [[NSDictionary alloc]   initWithObjectsAndKeys:@"contact_name", @"kumar",@"designantion",@"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, @"OfficeContactPerson", nil];

NSURL *url=[NSURL URLWithString:@"http://139.59.252.34:1337/office"];
NSData *postData=[[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];

[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postlength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error=[[NSError alloc]init];
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


if (!urlData){


    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Error"message:[NSString stringWithFormat:@"%ld",(long)(error.code)]
                                                 delegate:nil
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
    [alert show];

}
else
{
    NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"Response data ----->%@",responseData);
    NSError *error=nil;
    NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];


}
Sign up to request clarification or add additional context in comments.

17 Comments

fficeContactPerson": [ { "office": 29, "contact_name": "Priya", "designation": "Prop", "department": "ALL", "mobile": "1231231231", "email": "[email protected]", "incharge_status": null, "created_by": null, "modified_by": null, "id": 14, "createdAt": "2016-04-19T13:43:59.000Z", "updatedAt": "2016-04-19T14:25:36.000Z" } ]
hw cn i pass the above dat
is this dictionary or array ?
array inside dictionary
your above 'post' string is not in correct json formate which you are post to server. Make a key/value pair for each data using dictionary like you have done in your first line of code.
|
0

I'm new in ios app development but I try to solve.lets assume that these are your string.Try this code:

    NSString *messages-getModuleMessages=@"messages-getModuleMessages";
NSString * authtincateToken=@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =@"hai thios is textmessage";

// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,@"call",authtincateToken,@"authToken", accessSecretkey, @"accessSecret",inboxvalue,@"calotype",@"json",@"format",nil];

  // convert your dictionary to NSData
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
 // this is your service request url
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];
 // set the content as format
 [request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
  // this is your response type        
 [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
   NSError *err;
  NSURLResponse *response;
   // send the synchronous connection
   NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
   // here add your server response NSJSONSerialization
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; 

  // if u want to check the data in console
  NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", tmp);

Comments

0

Try below line of code and put them place of first two line of line code. Problem is only there.

    NSDictionary *dict = [[NSDictionary alloc]   initWithObjectsAndKeys:@"contact_name", @"kumar",@"designantion",@"sales", nil];
    NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSArray arrayWithObject:dict], @"OfficeContactPerson", nil];
NSData *POST_Params = [NSJSONSerialization dataWithJSONObject:urlParams options:NSJSONWritingPrettyPrinted error:nil]; // Pass these post data in request

Hope this will work for you!!

4 Comments

fficeContactPerson": [ { "office": 29, "contact_name": "Priya", "designation": "Prop", "department": "ALL", "mobile": "1231231231", "email": "[email protected]", "incharge_status": null, "created_by": null, "modified_by": null, "id": 14, "createdAt": "2016-04-19T13:43:59.000Z", "updatedAt": "2016-04-19T14:25:36.000Z" } ]
and also i have some of the text fields like name shop name like dat
br0 officecontactpersn is key then after array
In JSON [] means array and {} means dictionary. have you tried as per my answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.