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.
I see it as manly separating the database from you app. If you use JSON instead of just straight SQL, it give you the ability to switch out databases and create new views. For example you get sick of MYSQL and want to try out one of those fancy new NOSQL db like Mongodb, instead of rewritting your entire iphone app, you just hard to rewrite one php script. Another example would be, if you app is goin good and you want to create and android version, or a web version, JSON makes this easier, only have to install a JSON library and away you go!
精彩评论