I have an iPhone app that uses ASIHTTPRequest to post data to a php file, which then uses sql to update the database accordingly.
What’s bugging me is I keep reading that I should encode my posted data in JSON format. Can somebody explain to me the point in this? Why should I encode in JSON format? What are the benefits, needs for this..
EDIT:
Here is how I am posting my data:
-(void) postToDB:(NSString*) msg{
NSString *myphp = @"http://localhost:8888/databases/test.php";
NSURL *url = [NSURL URLWithString:myphp];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:msg forKey:@"message"];
[request setDelegate:self];
[request startAsynchronous];
}
Encapsulating your data in a JSON structure helps creating a structured communications protocol with your server. Without going as far as this depending on your needs, take a look at the specs for JSON-RPC for example. This allows you to have a fully-defined protocol for exchanging data, where methods are always passed the same way, errors are always returned the same way too.
The use of JSON, JSON-RPC, SOAP, or any other “envelope” is, strictly speaking, never mandatory. It’s just a good practice of standardizing communications over the wires.
Also, I don’t know if
setPostValue:ForKey:automatically escapes characters when needed, but imagine you’re sending a GET to http://whatever/get.php?nickname=nick&with?special@chars&password=qzerty.What happens here? your PHP script won’t be able to parse the “nickname” and “password” fields correctly.
Encapsulating your data in JSON with the help of a JSON framework (you can turn a NSString dictionary to a JSON structure flawlessly in a single line of code) helps preventing this kind of situation.