////VIEWCONTROLLER.M//03-post uploading JSON////Created by Jerry on 15/10/10.//Copyright (c) 2015 Jerry. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib. //1. URLNsurl *url = [Nsurl urlwithstring:@"http://127.0.0.1/post/postjson.php"]; //2. Post RequestNsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachepolicy:1timeOutInterval:2.0f]; //2.1 Set HttpMethodRequest. HttpMethod =@"POST"; //2.2 UpLoad JSON Type Data//serialization, converting nsarray/nsdictionary into binary data of a special data type. //deserialization converts binary data returned by the server to Nsarray/nsdictionaryNsdictionary *dict1 = @{@"name":@"Xiaofeng",@" Age":@" -"}; Nsdictionary*dict2 = @{@"name":@"Xiaosan",@" Age":@" +"}; Nsarray*array =@[dict1,dict2]; /**-Top level object was an Nsarray or nsdictionary top node is a dictionary or array-all objects is NSString, NSNumber, Nsarr Ay, nsdictionary, or NSNull all objects are NSString, NSNumber, Nsarray, nsdictionary, or Nsnull-all dictionary keys is Nsstrings all dictionary keys are nsstring-nsnumbers is not NaN or infinity Nsnumbers must be specified, cannot be infinity + (BOOL) Isvali Djsonobject: (id) obj; Used to verify that a given object can be serialized*/ //nsstring *str = @ "{\" username\ ": \" xiangfeng\ ", \" age\ ": \" 18\ "}"; if(![nsjsonserialization Isvalidjsonobject:array]) {NSLog (@"The format is not correct and cannot be serialized! "); return ; } request. Httpbody= [Nsjsonserialization datawithjsonobject:array options:0Error:null]; //Connection[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) { //one processing of deserialization IDresult =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"%@", result); }]; }- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end
POST Upload JSON data