I want to post an array value in JSON.
Below is my code :
-(void)getConnection {
NSArray *comment=[NSArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSURL *aurl=[NSURL URLWithString:#"http://sajalaya.com/taskblazer/staffend/form/iphonearraytest.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:aurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
// NSString *new = [comment JSONString];
// NSArray *new=[comment jsonvalue];
NSString *postString=[NSString stringWithFormat:#"tag=&comment=%#&total=%#",new,#"4"];
NSLog(#"this is post string%#",postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
We don't know your question, but my answer is short and simple. You should use great open source library for this, which is: AFNetworking, and do request like this:
_httpClient = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:#"http://sajalaya.com"]];
[_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
new, #"comment",
#4, #"total,
nil];
NSMutableURLRequest *request = [self.httpClient requestWithMethod:#"POST"
path:#"/taskblazer/staffend/form/iphonearraytest.php"
parameters:params];
request.timeoutInterval = 8;
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
Please use the following Mutable Array Operation componentsJoinedByString.
e.g.
NSMutableArray *commennts=[NSMutableArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSString* strCommentsJoin = [commennts componentsJoinedByString:#","]; // Please use your separator
Related
I want to wait until server reponse and parse XML done, then call another function. How can i do that? I used this code to send request to server and use NSXMLParser to parse XML response.
NSURL *url1 = [NSURL URLWithString:#"linkserver"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
NSDictionary *params1 = #{
#"a" : vd;
#"b" : #"all"
};
NSMutableURLRequest *afRequest = [httpClient requestWithMethod:#"GET" path:nil parameters:params1] ;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
[self parseXMLFile:parsexmlinput];// parse xml
[self getItemFromStatus];// wait to call another function at here???
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
Please give me any suggestion. Thanks much
You have to make your request synchronous.
refer code something like:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friends/ids.json?"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
check this tutorial Ray Wenderlich using AFnetworking.
Using blocks and callbacks
- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}
You can do it in synchronous way...
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:[url path] parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if(error) {
errorCallback(error, nil);
} else {
//parse the xml here
}
OR
You can achive it by adding [operation waitUntilFinished],after it's added to the operation queue.Refer this==>Can AFNetworking return data synchronously (inside a block)?
OR
EDIT: In case you don't want to use the AFNetworking library.I prefer this way.
NSString *action_Post =[[NSString alloc] initWithFormat:#"authToken=%#",theMutableString];
NSURL *action_Url =[NSURL URLWithString:#"ur url here"];
NSData *action_PostData = [action_Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *action_postLength = [NSString stringWithFormat:#"%d", [action_PostData length]];//your parameter to be posted here
NSMutableURLRequest *action_Request = [[NSMutableURLRequest alloc] init];
[action_Request setURL:action_Url];
[action_Request setHTTPMethod:#"POST"];
[action_Request setValue:action_postLength forHTTPHeaderField:#"Content-Length"];
[action_Request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[action_Request setHTTPBody:action_PostData];
NSURLResponse *action_response;
NSData *action_Result = [NSURLConnection sendSynchronousRequest:action_Request returningResponse:&action_response error:&error];
if (!action_Result)
{
NSLog(#"Error");
}
else
{
//Parse your xml here
//call ur function
}
Modify it according to your GET/PUT methods.But i suggest you to go for POST method,as it is refered to be as secured one.
I have JSON format like below i need to post request to sever but the response from the server is error 500.
{"firstName":"Sharath K", "lastName":"babu",
"moMerchantAddresses":[{"email":"abc#abc.co.in"}]} >
NSMutableArray *objects = [NSMutableArray arrayWithObjects:#"Sharath",#"babu",#"[{\"email\":\"abc#abc.co.in\"}]", nil];
NSMutableArray *keys = [NSMutableArray arrayWithObjects:#"firstName",#"lastName",#"moMerchantAddresses", nil];
NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
ServiceInterface *service = [[ServiceInterface alloc] init];
service.theDelegate = self;
service.theSuccessMethod = #selector(responseMerchantCreationService:);
service.theFailureMethod = #selector(requestFailedWithError:);
[self addServiceInterfaceToServiceStack:service];
NSString* stringURL = [kBase_URL stringByAppendingString:#"/merchant/create"];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[request setTimeoutInterval:30.0f];
NSLog(#"request file :: %#",request);
[service startWithRequest:request];
service = nil;
Please Help me in this
It may helps you .
NSMutableDictionary *emailDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[emailDict setObject:#"abc#abc.co.in" forKey:#"email"];
NSMutableArray *emailArr = [[NSMutableArray alloc] init];
[emailArr addObject:emailDict];
NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[mainDict setObject:#"Sharath" forKey:#"firstName"];
[mainDict setObject:#"babu" forKey:#"lastName"];
[mainDict setObject:emailDict forKey:#"moMerchantAddresses"];
Now change this mainDict to NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];
I am new in iOS. I created a JSON NSDictionary like this:
NSArray *keys = [NSArray arrayWithObjects:#"User", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"Ali", #"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
And then I could convert it to NSString via two mechanisms:
1)
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSString *jsonString = nil;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
2)
NSString *jsonString = [jsonDictionary JSONRepresentation];
In the second way I get this warning :
Instance method '-JSONRepresentation' not found (return type defaults to 'id')
But when I run the project, both of the mechanisms works fine:
NSLog(#"Val of json parse obj is %#",jsonString);
Do you know how can I remove the warning in the second way?
My main goal is POST this json String to an external database using RESTful Web Service.
Basically which way is better considering my main goal?
You should use NSJSONSerialization as it is faster and comes directly with iOS SDK as long as your "target audience" is iOS5+
To POST the data to your web service you need the create a request along these lines...
NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"value1", #"value2", nil]
forKeys:[NSArray arrayWithObjects:#"key1", #"key2", nil]];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"your_webservice_post_url"]];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:jsonData];
NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
Please read up on NSURLConnectionDelegate protocol.
For iOS 5.0 > :
Use NSJSONSerialization like this :
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%# Error:%#", resultAsString,error);
For < iOS 5 :
Use json-framework a third party library that uses category for NSDictionary to provide json string :
NSString *jsonString = [dictionary JSONRepresentation];
//with options
NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
This will help you... Convert NSDictionary to JSON with SBJson
use this way i hope it will help you
NSArray *keys = [NSArray arrayWithObjects:#"User", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"Ali", #"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error = nil;
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"\n\n\n id for json==%# \n\n\n\n\n",result);
JSON DEFAULT METHOD......
+(NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method {
NSDictionary *returnResponse=[[NSDictionary alloc]init];
#try {
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method];
if(postData != nil)
{
[urlRequest setHTTPBody:postData];
}
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"text/html" forHTTPHeaderField:#"Accept"];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
returnResponse = [NSJSONSerialization
JSONObjectWithData:urlData
options:kNilOptions
error:&error];
} #catch (NSException *exception) { returnResponse=nil; } #finally { return returnResponse; } }
Return Method :
+(NSDictionary )methodName:(NSString)string {
NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = #"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:#"POST"];
return returnResponse;
}
I'm new in iPhone and I'm trying to convert NSMutable array to json string then send this string to php file using request, and then print it again using respond to NSLog to ensure that it has been send successfully. So I wrote the following code in viewDidLoad
NSString *phpUrl = #"http://dt-works.com/eman/bookMarks.php";
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"one", #"two", #"three", nil];
NSMutableArray *arrayValue1 = [[NSMutableArray alloc] initWithObjects:#"1", #"2", #"3", nil];
NSMutableArray *arrayValue2 = [[NSMutableArray alloc] initWithObjects:#"11", #"22", #"33", nil];
NSDictionary *theReqDictionary1 = [NSDictionary dictionaryWithObjects:arrayValue1 forKeys:arrayKey];
NSDictionary *theReqDictionary2 = [NSDictionary dictionaryWithObjects:arrayValue2 forKeys:arrayKey];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:theReqDictionary1,theReqDictionary2, nil];
NSString *jsonString = [myArray JSONRepresentation];
NSLog(#"%#", jsonString);
NSDictionary *questions = nil;
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:jsonString forKey:#"jsonString"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request2 error];
[request2 startSynchronous];
if (!error) {
NSData *response = [request responseData];
NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(#"Data: %#", questions);
}
and the code in bookMarks.php is:
$handle = fopen('php://input','r');
$jsonInput = $_POST['jsonString'];
print_r($jsonInput);
but it gives me:
[{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
Data: (null)
and I want Data to be as: [{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
how to do this??
Try this, instead of posting the JSON string with a key, you need to post it as Data to your script to be read in. Currently in your script you aren't even using $handle for anything...
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeOutSeconds:120];
[request setDelegate:self];
And your php code..
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded);
I am trying to send the data to server and get the response. Data is reaching server but I am not getting any response. The value of response data is nil bcd of which it's throwing an exception,
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x4e2dd70 {NSLocalizedDescription=Unexpected end of string}"
Can anyone pls help me....
My code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *theError = NULL;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString* jsonString = [jsonDictionary JSONRepresentation];
SBJSON *jsonParser = [SBJSON new];
[jsonParser objectWithString:jsonString];
NSLog(#"Val of json parse obj is %#",jsonString);
[request setHTTPMethod:#"POST"];
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
NSMutableString* stringData= [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [stringData JSONValue];
NSString *json_message=[jsonDictionaryResponse objectForKey:#"message"];
printf("Json string is %s **********",[json_message UTF8String]);
I'm not privy of the particulars of your webservice, but the code below might be the source of your problem (or at least one of them!)
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
You are sending the request before setting the body, which I assume should include your jsonString contents. Plus you're assigning your jsonString to a header field, are you sure that is what you want? Here's a guess at what might work:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:jsonString];
responseData = // rest of your code here....
I suggest you have a good look through that code as it is a mess at the moment! You have two NSURLConnection requests going there, one asynchronous and one synchronous, it's kind of hard to understand what/why you are doing all of this so check Apple's documentation for NSURLConnection and tidy up your code...
[EDIT]
Here's my suggestion for you:
NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [string JSONValue];
[string release];
[theResponse release];
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:req];
[request setTimeoutInterval:15.0];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSError *dataError;
NSMutableDictionary * jsonDict = [[NSMutableDictionary alloc]init];
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&dataError];
NSLog(#"jsonDict:%#",jsonDict);
}
Try this :
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];