How to pass Json structure to Webservice using NSDictionary - objective-c

I need to pass a JsonObject to a webservice and for now I find out I should use an NSDictionary, what I tried is this:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"myurl"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"a#aaa.com", #"Email",
#"123", #"Phone",
#"123", #"Mobile",
#"a", #"Name",
#"a", #"Surname",
#"a", #"AddressType",
#"a", #"Address",
#"1", #"StreetNumber",
#"A", #"InternalStreetNumber",
#"3", #"ZIPCode",
#"a", #"City",
#"a", #"ProvinceCode",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
But it doesn't work and the Webservice doesn't return anything, the problem is that my structure should look like this:
userData:{
Email: "a#aaa.com",
Phone: "123",
Mobile: "123",
Name: "name",
Surname : "surname",
AddressType: "a",
Address: "a",
StreetNumber: "12",
InternalStreetNumber: "B",
ZIPCode: "123",
City: "a",
ProvinceCode: "a"
}
And I can't understand how to recreate a structure like this. Do I need to use NSDictionary? How can I possibly fix the problem?

You can try this
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setTimeoutInterval:Request_TimeOut_Time];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Set post body
if (postDict) //you dictionary
[request setHTTPBody:[[postDict JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]];

To send NSDictionary as a json object, you need to create proper structure of dictionary.
First convert into NSData. After that convert into NSString and post as json object.
In your Example :
Create a dictionary:
NSDictionary *tmp;
Then:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error:&error];
After converting into NSData, you need to convert it into NSString.
NSString *jsonString = [[NSString alloc] initWithData:jsonDataencoding:NSUTF8StringEncoding];
And this jsonString can be send as json object in a webservice.

Related

iPhone POST request with JSON data

I am building my first iPhone application and have run into problems trying to POST json data to my MongoDB database.
This is my code thus far:
NSString *post = [NSString stringWithFormat:#"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://myURL/users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
I get this response in the console:
2014-06-10 16:07:09.758 SocialEyez[2226:70b] Reply: {
"_id": "5397656dd7ec395c1b808230"
}
So even though the POST seems to go through fine, there is something wrong with my formatting which prevents the JSON data from being entered.
I've tried to format the NSString a hundred different ways but nothing seems to work.
Please help me out!!
EDIT:
When I send this request over jQuery:
jQuery.post("http://site/users", { "name": "George Washington", "reputation": "pres", "phone_number": "1234" }, function (data, textStatus, jqXHR) { console.log("Post resposne:"); console.dir(data); console.log(textStatus); console.dir(jqXHR); });
I get the following response:
_id: "53978f4cd7ec395c1b808247"
name: "George Washington"
reputation: "pres"
phone_number: "1234"
This example assumes that the post data should be JSON.
Create the JSON from a dictionary, let NSJSONSerialization add the JSON syntax.
// #"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"
// Create the dictionary
NSDictionary *postDict = #{#"name":#"blah", #"reputation":#"100", #"phone_number":#"1234"};
// Create the JSON data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];
// Just for this example: display the jsonData as an ASCII string
NSLog(#"jsonData as String: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog output:
jsonData: <7b226e61 6d65223a 22626c61 68222c22 72657075 74617469 6f6e223a 22313030 222c2270 686f6e65 5f6e756d 62657222 3a223132 3334227d>
jsonData as String: {"name":"blah","reputation":"100","phone_number":"1234"}

Sending images through json getting failed

Code:
NSData *imgd=UIImageJPEGRepresentation(Obj.thumbImage, 0.5);
[imgName insertObject:Obj.imageName atIndex:i];
[imgName1 insertObject:imgd atIndex:i];
[dic setObject:imgName forKey:#"name"];
[dic setObject:imgName1 forKey:#"image"];
[asiLoadingFormRequest setPostValue:contactName forKey:#"receivername"];
[asiLoadingFormRequest setPostValue:[dic JSONRepresentation] forKey:#"imagedata"];
Is it correct to way sending images through json?When i call server i am getting following error message
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"Unsupported value for key image in object\" UserInfo=0x9a611f0 {NSUnderlyingError=0x9a4a290 \"JSON serialisation not supported for NSConcreteMutableData\", NSLocalizedDescription=Unsupported value for key image in object
Is it problem with Json that does not support for images?I have no idea about this problem.any help will be appreciated.thanks in advance.
Try this:
Encoding Part:
First Add Base64 class into your project.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http:xxx.me.com/me.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSData *imageData = UIImagePNGRepresentation ([UIImage imageWithContentsOfFile: #"ur PNG image path"]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSArray *keys = [NSArray arrayWithObjects:#"image_id",#"image_name","image",nil];
NSArray *objects = [NSArray arrayWithObjects:#"22",#"myImageName.png",imageString,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
For Decoding the same on the server side(if your using php) refer this.
You cannot send NSData as JSON, if you want to send an image over JSON you have to first encode it in Base64 and then decode it on the server
Take a look at this
https://github.com/l4u/NSData-Base64

Sending JSON through POST not working - Objective C

I am sending a JSON string to our server using the POST method. What should happen is that it should return a response showing "Array(JSON String) Array(JSON String)". The response contains two arrays: The first array is populated if I used the POST method, while the second array is populated if I use the GET method. I tried sending the JSON through GET method and indeed, the second array was populated. However, when I tried to send JSON through POST method, both arrays are returned empty.
Here is the code I used:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:sqlArray options:NSJSONWritingPrettyPrinted error:&error];
NSURL *url = [NSURL URLWithString:#"http://myurl/xmlrpc/imwebsrvcjson.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", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSData *result =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if (error == nil){
NSLog(#"The Result string: %#", returnString);
}
Can you tell me what is wrong with my code?
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.

passing JSON data with hebrew values problems (UTF8?)

i have this method -
NSArray *objects = [NSArray arrayWithObjects:appDelegate.UserID,itemName.text,#"1",#"1",itemDegem.text,itemDescription.text, nil];
NSArray *keys = [NSArray arrayWithObjects:#"userId",#"itemName",#"itemCategoryId",#"regionId",#"degemName",#"itemDescription", nil];
NSDictionary *registerDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonRequest = [registerDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://www.somedomain.com/method"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
self.responseData = [NSMutableData data];
}
but when i send strings in my objects that not in english im getting error from the server.
now, i know its a UTF8 problem, but i did set it to be UTF8. can someone please help me figure it out ?
I think the error is strlen([jsonRequest UTF8String]) is not equal to [jsonRequest length].
Use NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; to convert a NSString into NSData using UTF8 encoding.

JSON POST Request on the iPhone (Using HTTP) Problems

Im having problems with my request to a asp .net mvc web service. I read in a thread a while ago that its possible to find out what the server wants the the request's content-type to be etc. I get no error when compiling but when I do the actual request nothing happens and in the log of the server it only says (null) (null). There is no problem doing the GET request and fethcing all objects that are in the list. Can anyone please help me with this irritating bug? here is the code:
//----------------GET request to webservice works fine----------------------------------------
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod: #"GET"];
NSData *response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *stringResponse = [[NSString alloc] initWithData: response encoding: NSUTF8StringEncoding];
//NSLog(#"stringResponse is %#", stringResponse);
//--------------------------------------------------------------------------------------------
NSString *twitterTrendsUrl=#"http://search.twitter.com/trends.json";
NSString *output=
[NSString stringWithContentsOfURL:[NSURL URLWithString:twitterTrendsUrl]];
id theObject= [output JSONValue];
NSLog(#"TWITTER: %#",theObject);
*/
//--------------------------------------------------------------------------------------------
NSURL *url = [NSURL URLWithString:#"http://errorreport.abou.se/Errors/1.0"];
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\"}";
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\",\"Address\":\"smedjegatan\",\"StreetNumber\":\"34\",\"Feedback\":\"True\",\"FeedbackWay\":\"Telefon\"}";
NSMutableDictionary* jsonObject = [NSMutableDictionary dictionary];
//NSMutableDictionary* metadata = [NSMutableDictionary dictionary];
//[metadata setObject:#"NewLoc" forKey:#"Uri"];
//[metadata setObject:#"Location.NewLoc" forKey:#"Type"];
//[jsonObject setObject:metadata forKey:#"__metadata"];
[jsonObject setObject:#"Gurras" forKey:#"Description"];
[jsonObject setObject:#"Klotter" forKey:#"Category"];
[jsonObject setObject:#"smedjegatan" forKey:#"Address"];
[jsonObject setObject:#"34" forKey:#"StreetNumber"];
[jsonObject setObject:#"True" forKey:#"Feedback"];
[jsonObject setObject:#"Telefon" forKey:#"FeedbackWay"];
// ... complete the other values
//
NSString* jsonRequest = [jsonObject JSONRepresentation];
// jsonString now contains your example strings.
NSLog(#"Request: %#", jsonRequest);
//NSURL *url = [NSURL URLWithString:#"https://mydomain.com/Method/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[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", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
//[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"returnData: %#", returnString);
I can also add an example of how to talk to the service with javascript:
<script type="text/javascript">
var obj = { "Description": "det kanske funkar" };
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Errors/1.0",
dataType: "json",
contentType: "application/json",
processData: true,
data: '{"Description": "STeffeent asdasd", "Category": "Miljö", "Address": "Bogatan","StreetNumber": "14", "Feedback": "true", "FeedbackWay": "Brev"}',
success: function (data) {
$("#result").text(data.Description);
}
});
});