POST 上传 JSON 数据

  

//
//  ViewController.m
//  03-post上传json
//
//  Created by jerry on 15/10/10.
//  Copyright (c) 2015年 jerry. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 1. url
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/post/postjson.php"];
    
    // 2. post Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:2.0f];
    // 2.1 set HTTPMethod
    request.HTTPMethod = @"POST";
    
    // 2.2 UpLoad JSON Type Data
    // 序列化,将NSArray/NSDictionary转换成特殊数据类型的二进制数据。
    // 反序列化 将服务器返回的二进制数据转成NSArray/NSDictionary
    NSDictionary *dict1 = @{@"name":@"xiaofeng",@"age":@"18"};
    NSDictionary *dict2 = @{@"name":@"xiaosan",@"age":@"21"};
    
    NSArray *array = @[dict1,dict2];
    /**
     - Top level object is an NSArray or NSDictionary
     顶级节点是字典或者数组
     - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
     所有的对象是 NSString, NSNumber, NSArray, NSDictionary, or NSNull
     - All dictionary keys are NSStrings
     所有字典的key 是 NSString
     - NSNumbers are not NaN or infinity
     NSNumbers必须指定,不能是无穷大
     
     + (BOOL)isValidJSONObject:(id)obj;
     用来检验给定的对象是否能够被序列化
     */
    //    NSString *str = @"{"username":"xiangfeng","age":"18"}";
    if (![NSJSONSerialization isValidJSONObject:array]) {
        NSLog(@"格式不正确,不能被序列化!");
        return ;
    }
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
    
    // connection
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 反序列化的一个处理
        id result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",result);
    }];

    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/pengpengzhang/p/4865751.html