异步POST请求解析JSON

一、创建URL

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
   
二、创建一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
   
三、设置请求方法
request.
HTTPMethod = @"POST";
   
五、设置请求体(请求參数)
// 创建一个描写叙述订单信息的JSON数据
NSMutableDictionary *orderInfo = [NSMutableDictionary dictionary];
orderInfo[@"shop_id"] = @"123;
orderInfo[@"shop_name"] = @"123";
orderInfo[@"user_id"] = @"123";
// 将字典转化成data
NSData *bodyData= [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.
HTTPBody bodyData;
   
六、设置请求头:这次请求体的数据不再是普通的參数。而是一个JSON数据
[request
setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   
七、发送请求
[
NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
   
if (data == nil || connectionError) return;
   
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
   
NSString *error = dict[@"error"];
   
if (error) {
         [
MBProgressHUD showError:error];
   }
else {
         
NSString *success = dict[@"success"];
         [
MBProgressHUD showSuccess:success];
   }
}];

注意:
 [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil]
将JSON转化成二进制数据
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
将二进制数据转成JSON
设置请求头:这次请求体的数据不再是普通的參数,而是一个JSON数据
[request
setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];