发送JSON数据到服务器

  • 方案一 : 把JSON格式的字符串序列化成JSON的二进制
#pragma 方案一 : 把JSON格式的字符串序列化成JSON的二进制
- (void)POSTJSON_01
{
    NSString *jsonStr = @"{\"name\":\"大发明家\"}";

    // 把JSON格式的字符串序列化成JSON的二进制
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    [self postJsonWith:jsonData];
}
  • 方案二 : 把字典序列化成JSON格式的二进制
#pragma 方案二 : 把字典序列化成JSON格式的二进制
- (void)POSTJSON_02
{
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"亚索" forKey:@"name"];

    // 把字典序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    [self postJsonWith:jsonData];
}
  • 方案三 : 把数组序列化成JSON格式的二进制
#pragma 方案三 : 把数组序列化成JSON格式的二进制
- (void)POSTJSON_03
{
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"牛头" forKey:@"name"];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"石头人" forKey:@"name"];
    NSArray *arr = @[dict1,dict2];

    // 把数组序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
    [self postJsonWith:jsonData];
}
发送json数据到服务器的主方法,传入json数据的二进制
#pragma 发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
    // URL
    NSURL *URL = [NSURL URLWithString:@"http://localhost/php/upload/postjson.php"];
    // 请求
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:URL];
    // 设置请求方法
    requestM.HTTPMethod = @"POST";
    // 设置请求体
    requestM.HTTPBody = jsonData;

    // 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 处理响应
        if (error == nil && data != nil) {

            // 反序列化
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

        } else {
            NSLog(@"%@",error);
        }
    }] resume];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值