How to create JSON string for HTTP Request in iOS
i have these values:
{"name":"customer6","pass":"customer6", "mail":"customer6#xy.com","user_roles":"5", "field_login_pin_value":{"und":[{"value":"2324"}]} }
So how to make JSON string out of this data ?
Here is my code :
NSArray *keys = [NSArray arrayWithObjects:#"name",#"pass",#"mail",#"user_roles",#"field_login_pin_value", nil];
NSArray *objects = [NSArray arrayWithObjects:#"customer6",#"customer6",#"customer6#xy.com",#"5",#"{\"und\":[{\"value\":\"2324\"}]", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xxxxxxxx/register.json"]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
nsconnection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
When I hit the web-service request, I get the following response:
"form_errors" = {
"field_login_pin_value][und][0][value" = "PIN value field is required.";
};
}
I always get the same error
Can anyone let me know what is wrong with my implementation ?
I'd imagine that JSONRepresentation is formatting "{\"und\":[{\"value\":\"2324\"}]" as the literal string it is, not as a value within a dictionary within an array within a dictionary. You should make the whole dict-array-dict structure. This will all be easier if you use array and dictionary literals:
NSDictionary *jsonDictionary = #{
#"name" : #"customer6",
#"pass" : #"customer6",
#"mail" : #"customer6#xy.com",
#"user_roles" : #"5",
#"field_login_pin_value" : #{
#"und":#[
#{
#"value" : #"2324"
}
]
}
};
You can, of course, coalesce the pin_value value to a single line, this is just for clarity.
Related
in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
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:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];
Good morning,
How can I load a MySQL query result into a UILabel in my iOS app? I need to display the name of the user, the followers and also the profile image. How can I do that?
I have created the storyboard with the UILabels and the UIImageView but now I need to load the data from my MySQL database and I'm a little bit lost.
Thanks in advance.
You can get data with JSON.
NSMutableURLRequest * requestTransfer;
NSString *strUrl = #"www.yoursite.com/Mobile/GetUser";
requestTransfer = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strUrl]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[requestTransfer setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[requestTransfer setHTTPMethod:#"POST"];
NSHTTPURLResponse * response;
NSError* error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:requestTransfer returningResponse:&response error:&error];
NSDictionary *dicUsers = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
You can use dictionary like that.
NSString* strID = [dictionary objectForKey:#"UserID"];
NSString* strName = [dictionary objectForKey:#"UserName"];
NSString* strLink = [dictionary objectForKey:#"ImageLink"];
yourlabel.text = strName;
I'm sending base64 string to php server and its working well. Now I want to send another parameter as a string. Can anyone tell me what code need to add in below code.
Below code is working good for single parameter. How can we modify it for multiple parameters?
NSData *data = [UIImageJPEGRepresentation(imgeview.image,90) base64Encoding];
// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:#"question_image=%#",data];
myRequestString = [myRequestString stringByReplacingOccurrencesOfString:
#"+" withString:#"%2B"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String]
length:[myRequestString length]];
request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://192.168.0.101/Mobile_tutor/webservice/question_details.php"]];
// set Request Type
[request setHTTPMethod:#"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody:myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes]
length:[returnData length]
encoding:NSUTF8StringEncoding];
NSLog(#"-------------%#",response); // here you get reasponse string
For the network operation these is better supporting API like AFNetworking available witch work async and way better to handle
Tutorials for AFNetworking
Get from here
NSArray *keys = #[#"UserID", ];
NSArray *objects = #[#(userId)];
NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:BaseURLString]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"services/UserService.svc/GetUserInfo"
parameters:parameter];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError* error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
// do what ever
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Given a NSDictionary "params" whose keys and values are strings and where every entry represents one parameter (name/value) you can define a helper category:
#interface NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded;
#end
dataFormURLEncoded returns a properly encoded character sequence from the given parameters in the dictionary.
The encoding algorithm is specified by w3c: URL-encoded form data / The application/x-www-form-urlencoded encoding algorithm
It can be implemented as follows:
First, a helper function which encodes a parameter name, respectively a parameter value:
static NSString* x_www_form_urlencoded_HTML5(NSString* s)
{
// http://www.w3.org/html/wg/drafts/html/CR/forms.html#application/x-www-form-urlencoded-encoding-algorithm , Editor's Draft 24 October 2013
CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?#~");
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)s,
charactersToLeaveUnescaped,
legalURLCharactersToBeEscaped,
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
Finally, dataFormURLEncoded composes the character sequence of the encoded parameters. A "parameter" will be composed by concatenating the encoded name, = and encoded value:
parameter := name "=" value
Then, the parameter list will be composed by concatenating the parameters by separating them by a "&":
parameters := parameter ["&" parameter]
It can be implemented as below:
#implementation NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded {
NSMutableData* data = [[NSMutableData alloc] init];
BOOL first = YES;
for (NSString* name in self) {
#autoreleasepool {
if (!first) {
[data appendBytes:"&" length:1];
}
NSString* value = self[name];
NSData* encodedName = [x_www_form_urlencoded_HTML5(name) dataUsingEncoding:NSUTF8StringEncoding];
NSData* encodedValue = [x_www_form_urlencoded_HTML5(value) dataUsingEncoding:NSUTF8StringEncoding];
[data appendData:encodedName];
[data appendBytes:"=" length:1];
[data appendData:encodedValue];
first = NO;
}
}
return [data copy];
}
#end
Note: The character sequence encodes the strings using Unicode UTF-8.
Example:
Given your parameters:
NSDictionary* params = #{#"a": #"a a", #"b": #"b+b", #"c": #"ü ö"};
NSData* encodedParamData = [params dataFormURLEncoded];
Now, encodedParamData will be added to your body whose content type is application/x-www-form-urlencoded.
The encoded parameter string becomes:
a=a+a&b=b%2Bb&c=%C3%BC+%C3%B6
I am using Parse.com as a backend of my application, where I am currently storing the data there.
The data is a list of video game consoles. I was able to make an output of it, but instead of JSON data, the output is a big NSMutableArray.
This is my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSError *error;
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"The list: %#", listOfConsoles);
}
The output:
The list: {
results = (
{
createdAt = "2013-03-21T07:26:04.149Z";
name = PlayStation;
objectId = vloIK0MZIA;
updatedAt = "2013-03-21T07:26:04.149Z";
},
{
createdAt = "2013-03-21T07:26:34.209Z";
name = Wii;
objectId = RIRpgbznlq;
updatedAt = "2013-03-21T07:26:34.209Z";
},
{
createdAt = "2013-03-21T07:26:39.391Z";
name = Xbox;
objectId = xBNgHtJbrV;
updatedAt = "2013-03-21T07:26:39.391Z";
}
);
}
What I want the output to be:
{
"results" : [
{
"objectId" : "vloIK0MZIA",
"updatedAt" : "2013-03-21T07:26:04.149Z",
"createdAt" : "2013-03-21T07:26:04.149Z",
"name" : "PlayStation"
},
{
"objectId" : "RIRpgbznlq",
"updatedAt" : "2013-03-21T07:26:34.209Z",
"createdAt" : "2013-03-21T07:26:34.209Z",
"name" : "Wii"
},
{
"objectId" : "xBNgHtJbrV",
"updatedAt" : "2013-03-21T07:26:39.391Z",
"createdAt" : "2013-03-21T07:26:39.391Z",
"name" : "Xbox"
}
]
}
BY THE WAY
Why is it that when I have a separate NSData in the code:
NSData *JSONData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
And change my NSJSONSerialization to:
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
The output will be:
The list: {
error = unauthorized;
}
The first list is a NSDictionary with a single key called "results" which has an NSArray of NSDictionaries.
The second list is the same thing..
Edit 1.0:
Just to clarify, the second output is JSON, ok? Simply as that, just check here and validate yourself. The first one is the outputted JSON that is inside an NSObject. Of course there will be slight differences...
Your Authentication not done successfully. Please check APPLICATION_ID and REST_API_KEY values.
I was an idiot. I never realized that I tried to convert the JSON to something else, when I wanted the JSON data.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSString *listOfConsoles = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"%#", listOfConsoles);
}
Hi guys so i am using NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil] command to write the json. It looks fine and when i post to the Rails server the \"first name\" is still there. Can any one help
NSArray *objects = [NSArray arrayWithObjects:#"firstname", #"lastname",nil];
NSArray *keys = [NSArray arrayWithObjects:#"dave", #"lu", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];
NSArray *objects2 = [NSArray arrayWithObjects:#"utf8",
#"authenticity_token",#"check_i_ndatum", #"commit",nil];
NSArray *keys2 = [NSArray arrayWithObjects:#"1", #"xx",questionDict,#"Create Check i
Nadtum", nil];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:keys2 forKeys:objects2];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted error:nil];
NSURL * url =[NSURL URLWithString:#"http://192.168.1.105:3000/check_i_ndata"];
//the request
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
//bind req w/ json
[request setHTTPMethod:#"POST"];
//[request setValue:#"check_i_ndata" forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonRequestData length]]
forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonRequestData];
NSURLResponse * response = nil;
NSError *error =nil;
NSData *reslut =[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
OUTPUT->>>>in xcode
{
"commit" : "Create Check i Nadtum",
"authenticity_token" : "xx",
"utf8" : "1",
"check_i_ndatum" : {
"firstname" : "dave",
"lastname" : "lu"
}
}
OUTPUT ->>> ON RAILS SERVER
Started POST "/check_i_ndata" for 192.168.1.100 at 2012-07-29 10:25:37 -0700
Processing by CheckINdataController#create as */*
Parameters: {"{\n \"commit\" : \"Create Check i Nadtum\",\n \"authenticity_token\" :
\"xx\",\n \"utf8\" : \"1\",\n\"check_i_ndatum\" : {\n \"firstname\" : \"dave\",\n
\"lastname\" : \"lu\"\n }\n}"=>nil}
SHOULD LOOK LIKE THIS ->>> ON RAILS SERVER
{"utf8"=>"✓", "authenticity_token"=>"XtLdI2lWSfO6OL8OwZ9Kai+Cm7hFe16EH50zPfheGbs=",
"check_i_ndatum"=>{"firstname"=>"sdf", "lastname"=>"asdf",
"medicalID"=>"adsf", "checkedInDate(1i)"=>"2012",
"checkedInDate(2i)"=>"7", "checkedInDate(3i)"=>"29",
"checkinTime(1i)"=>"2012", "checkinTime(2i)"=>"7",
"checkinTime(3i)"=>"29", "checkinTime(4i)"=>"08",
"checkinTime(5i)"=>"40"}, "commit"=>"Create Check i ndatum"}
You haven't set the content type on your post request so it ends up getting interpreted as a normal form encoded post.
Adding a Content-Type header set to something like application/json should result in rails parsing the request as json
For example with respect to the code above this might look like:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];