The main method of the POST JSON is set Content-type to Application/json the remainder is to convert the class to JSON format binary number
-(void) Postjson: (NSData *) Data {
1. Url
Nsurl *url = [Nsurl urlwithstring:@ "http://127.0.0.1/postjson.php"];
2. Request
Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
2.1 HttpMethod
Request. HttpMethod = @ "POST";
2.2 Set Content-type, some servers when receiving data, will do the data type of verification
[Request setvalue:@ "Application/json" forhttpheaderfield:@ "Content-type"];
2.3 Setting up data
Request. Httpbody = data;
3. Connection
[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
NSLog (@ "%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]);
}];
}
An array of POST dictionaries or a separate dictionary
-(void) Postdict {
Nsdictionary *dict1 = @{@ "ProductId": @123, @ "ProductName": @ "Mac Pro"};
Nsdictionary *dict2 = @{@ "ProductId": @001, @ "ProductName": @ "IPhone 7"};
Nsarray *array = @[dict1, dict2];
serialization, before the data is sent to the server, the dictionary/array---binary data
Data parsing-deserialization, converting binary data returned by the server into a dictionary or model
NSData *data = [nsjsonserialization datawithjsonobject:array options:0 error:null];
[Self postjson:data];
}
KVC the properties of a class into a dictionary, and then serializes the dictionary
-(void) Postperson {
Parameters: Converting an array of incoming objects into a dictionary
ID obj = [self.person dictionarywithvaluesforkeys:@[@ "name", @ "age", @ "title", @ "height"]];
A top-level node, which is an array or dictionary
if (![ Nsjsonserialization Isvalidjsonobject:obj]) {
NSLog (@ "Invalid data format");
Return
}
NSData *data = [nsjsonserialization datawithjsonobject:obj options:0 error:null];
[Self postjson:data];
}
POST JSON (Dictionary custom class converted to JSON upload)