How to reach members of json with iOS - ios

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.

Related

Proper JSON encoding for HTTP POST request in iOS

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;
}
}

iOS 5 Json Serialization

I have used JSON Serialization to get json response, here i'mn getting all fine, but when i need to post some values as key value pair with the URL. I have done like this, but didn't get the result.
NSArray *objects = [NSArray arrayWithObjects:#"uname", #"pwd", #"req",nil];
NSArray *keys = [NSArray arrayWithObjects:#"ann", #"ann", #"login", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
// NSLog(#"Success");
}
}
NSURL * url =[NSURL URLWithString:#"URL_address_VALUE/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[result length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:result];
NSURLResponse *res = nil;
NSError *error = nil;
NSData *ans = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
if (error == nil) {
NSString *strData = [[NSString alloc]initWithData:ans encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
I don't know what goes wrong here... Please dudes help me..
There are multiple Errors in your Code, Use my Code as a Reference and compare it to yours and you'll get the Errors done by you.
The Below code is working correctly from the Point of View of Objective-C. There are some Errors regarding your URL or Service Side.
Working Code :
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"ann",#"uname",#"ann",#"pwd",#"login",#"req", nil];
NSLog(#"dict :: %#",dict);
NSError *error2;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error2];
NSString *post = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLength :: %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://exemplarr-itsolutions.com/dbook/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error3;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error3];
NSString *str = [[NSString alloc] initWithData:POSTReply encoding:NSUTF8StringEncoding];
NSLog(#"str :: %#",str);

Connection to Server successfully but got some crap after json format strings

I have successfully connected to a server, and getting correct json format String from it. Somehow 9 out of 10 times it return with something extra.. like some crap code i don't recognize. sometimes its just incomplete data. I wonder what I did wrong or what I didn't do..
does anyone has the same problem? and how can I fix it?
NSURL *siteURL = [NSURL URLWithString:tempSiteString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:siteURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30.0];
NSString *myRequestString = [NSString stringWithFormat:#"data=%#", sqlString];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[sqlString length]];
[request setHTTPMethod: #"POST" ];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
here is the code i change the received string to json
NSDictionary *tempNSDictionary = [resultString JSONValue];
if(tempNSDictionary.count==0)
{
return nil;
}
//NSLog(#"Check Point after dictionary");
NSArray *tempNSArray;
if(tempNSDictionary)
{
//NSLog(#"Check Point getArrayFromJsonString 1");
tempNSArray = [tempNSDictionary objectForKey:#"object_name"];
//NSLog(#"Check Point getArrayFromJsonString 2");
}
return tempNSArray;

Send JSON post data from iPhone Application Expressjs/Nodejs backend

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.

Getting JSON data From a URL Which contains .SVC?wsdl file in iOS 5?

Someone please help me in this query.
How to Get JSON data From a URL Which contains .SVC file in iphone (ios5)?
The link is like : http://156.160.45.118/api/Login.svc?wsdl (not original)
and parameters are: email and password.
So how can I verify the login credentials?
My code :
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://156.160.45.118/api/Login.svc?wsdl";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
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);
}
Finally i got my answer By researching lot of things.
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = http://156.160.45.118/api/Login.svc/login;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);

Resources