ios 发送 json ios怎么发送json数组_ios 发送 json


发送Json数据(纯Json)给服务器:

必要条件:

(1):使用post请求。

(2):设置请求头为(“application/json”)。

(3):设置请求体。(要传输的Json字串)。

//上传json字串
- (void)postJson{
    NSURL * url = [NSURL URLWithString:@"http://10.66.66.9:8080/ZLServer/userInfo"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置请求体
    NSDictionary * jsonDict = @{
                                @"username" : @"zl",
                                @"age" : @"123"
                                };
    //需要将Json字串转化成NSData类型
    NSData * data = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody = data;
    //发送请求

    NSURLSession * session = [[NSURLSession alloc] init];

    [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    }];
    //号外:开源的第三方库,比如ASI,AFN都可以以此种方式将Json数据传输到服务器
}

服务器端可以直接将接收到的json数据转换成model对象。
最后想说一句:策策。。。。。