I am using a method to call the Web Services and Upload the Transcription Audio File On the Server. The method is as follows:
- (NSDictionary *)UploadTranscriptionAudio:(NSString *)uploadfor forPN_ID:(NSString
*)pn_id forTaskFlag:(NSString *)taskflag documentPath:(NSString *)documentpath
forUserName:(NSString *)username file_path_msd:(NSString *)file_path_msd
audioFilePath:(NSString *)audiofilepath{
NSDictionary *response = nil;
NSURL * url = [NSURL URLWithString:[AppDelegate sharedInstance].str_webServiceUrl];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:uploadfor forKey:#"Uploadfor"];
[request setPostValue:pn_id forKey:#"PNID"];
[request setPostValue:taskflag forKey:#"task_flag"];
[request setPostValue:documentpath forKey:#"Path"];
[request setPostValue:username forKey:#"Username"];
[request setPostValue:file_path_msd forKey:#"file_path_msd"];
[request setFile:audiofilepath forKey:#"uploadedfile"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = (NSDictionary*)[request responseString];
NSLog(#"Response = %#",response);
return response;
}
return response;
}
This method is still returning me a NSstring in response. What i want is that this method should return me a NSDictionary. As I have to use the value for the keys inside that dictionary somewhere else. Can somebody help me on this.
hello shikher maddy says right n u can parse string as follow
if (responseString == NULL) {
// do something u want
} else {
NSDictionary *jsonResponse = [responseString JSONValue];
NSLog(#" %#",jsonResponse);
}
If I were you I would use SBJSONParser like this:
SBJsonParser *parser= [[SBJsonParser alloc] init];
NSDictionary *dictionnary = [parser objectWithString:responseString error:nil];
Related
I'm trying to use an AFHTTPRequestOperation (via an AFHTTPRequestOperationManager) to transmit some information (say, "foo = bar") to an backend expecting JSON, using a setup like this:
- (void) postTest {
NSString *completePath = #"https://httpbin.org/post";
NSDictionary *dataToJSONfy = #{#"foo":#"bar"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dataToJSONfy options:kNilOptions error:&error];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:#"POST" URLString:completePath parameters:nil];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
AFHTTPRequestOperation *operation =
[self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id JSON) {
NSLog(#"... success! %#", JSON);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"... failure! Error: %#", error);
}];
[self.operationQueue addOperation:operation];
}
Which shows up like this
{
args = {
};
data = "{\"foo\":\"bar\"}";
files = {
};
form = {
};
headers = {
[...]
};
json = {
foo = bar;
};
origin = [...];
url = "http://httpbin.org/post";
}
Question: what would I need to change in order to include my information ("foo = bar;") in the 'form =' section of the body rather than the 'json =' bit?
I want to include valid JSON (e.g. some server response stored earlier) in the post, but as per API specification, everything's supposed to be located under the 'form = {};' part. So I guess I want JSON as formdata.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dataToJSONfy options:kNilOptions error:&error];
//new!
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *bodyString = [NSString stringWithFormat:#"{'Form': '%#'}, jsonString]; //! not 100% what you want. I stick with valid JSON here
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:#"POST" URLString:completePath parameters:nil];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:bodyData]; //!
first you need to declare nsdictionary block just after the postTest method like
__block NSDictionary *dict=[NSDictionary alloc] init];
and in success block you should use
dict=[NSJSONSerlization JSONObjectWithData:JSON options:NSJSONReadingAllowFragments error:nil];
NSLog(#"... success! %#", dict);
Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}
I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.
I have used SBJsonParser and ASIFormDataRequest for Posting and JSON Parsing, like
NSString *urlStr = #"http:facebookpage/second/index.php";
NSURL *log_Url = [NSURL URLWithString:urlStr];
request = [ASIFormDataRequest requestWithURL:log_Url];
[ASIHTTPRequest setSessionCookies:nil];
[request setPostValue:uName.text forKey:#"uname"];
[request setPostValue:passWord.text forKey:#"pwd"];
[request setPostValue:#"login" forKey:#"req"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = [request responseString];
}
NSLog(#"%#",response);
Then For Parsing:
parser = [[SBJsonParser alloc]init ];
json_dic_values = [parser objectWithString:response error:nil];
NSString *status = [json_dic_values objectForKey:#"status"];
Url_pathforPages = [json_dic_values objectForKey:#"url"];
NSString *sessionID = [json_dic_values objectForKey:#"session_id"];
Here I need to know how can i do this same in NSJsonSerialization.
Everything is working fine in above method....
There are really only a few methods in NSJSONSerialization. Take a look at the documentation.
json_dic_values = [NSJSONSerialization JSONObjectWithData: [response dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: &error];
This is my code for sending a post request to a nodejs backend.
CLLocation* location = [locationManager location];
CLLocationCoordinate2D coord = [location coordinate];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://50.63.172.74:8080/points"]];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary* jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:coord.latitude], #"lat", [NSNumber numberWithFloat:coord.longitude], #"lng", nil];//dictionaryWithObjectsAndKeys:coord.latitude, nil]
NSString *postString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
Using express I'm getting the request.body back on the server but it looks like this:
{ '{\n "lat" : 0.0,\n "lng" : 0.0\n}': '' }
and I can't access it by just saying request.body.lat since it comes back as undefined.
I want the body to look like:
{ "lat":0.0, "lng":0.0}
Any idea on how to do that using express?
May this help you.
Please replace 0.0 with your actual coordiantes
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:#"0.0",#"0.0", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *requestString = [NSString stringWithFormat:
#"http://50.63.172.74:8080/points"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
NSLog(#"Error %#",errorReturned.description);
}
else
{
NSError *jsonParsingError = nil;
NSMutableArray *arrDoctorInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(#"Dict %#",arrDoctorInfo);
}
The problem is that after you use NSJSONSerialization to obtain a NSData object containing your JSON data, you then create postString from that data. Eliminate that unnecessary step, and just do:
[request setHTTPBody:jsonData];
And you should get the expected JSON in your server-side code.