【问题标题】:Objective-C How to send data to Http Post request with nested dictionary in headerObjective-C如何使用标题中的嵌套字典将数据发送到Http Post请求
【发布时间】:2017-11-28 12:31:18
【问题描述】:

我已经学习 Objective-C 几个月了。在那段时间里,我已经能够做一个基本的发布请求,但是我今天看到了一个包含嵌套字典的发布请求的标题。我不确定如何将数据传递给这样的 API。

我的问题是如何将数据发布到此 API。如果您能指出相关的阅读材料和教程以及此复杂 API 请求等示例或给出答案,我将不胜感激。

API 标头如下所示:

    { "header":
   { "id": "2312b24c-5b83-46f0-8670-5edc2b1d1672",
     "parentId": "3gyy-w325e-bebd-ddsfsdf",
     "countryCode": "IRELAND",
     "timestamp": "2017-10-13T08:39:14.638Z" },
  "myinfo":
   { "User": "intro",
     "contactPerson": "Newbee",
     "contact": "00000000",
     "notes": "hey guys i am new"
       
   }
    
}

这是我的代码,我需要多个字典的帮助。

    __block NSMutableDictionary *resultsDictionary;
      SMAMobileAPI *api = [SMAMobileAPI sharedSMAMobileAPI];
      NSMutableDictionary *bodyParams = [[NSMutableDictionary alloc]init];

      NSMutableDictionary *header = [[NSMutableDictionary alloc]init];
      [header setValue:@"2312b23c-5b83-46f0-8670-5edc2b1d1672" forKey:@"id"];
      [header setValue:@"2e3a015e-bebd-ddsfsdf" forKey:@"parentId"];
      [header setValue:@“IRELAND" forKey:@"countryCode"];
      [header setValue:@"2017-10-13T08:39:14.638Z" forKey:@"timeStamp"];

      NSMutableDictionary *myinfo = [[NSMutableDictionary alloc]init];
      [Case setValue:@“intro" forKey:@“User"];
      [Case setValue:@“newbie" forKey:@"contactPerson"];
      [Case setValue:@"+254 724474140" forKey:@"contactPersonNo"];
      [Case setValue:@"iOS case" forKey:@"notes"];

      [bodyParams setValue:header forKey:@"header"];
      [bodyParams setValue:myinfo forKey:@“myinfo"];

    if ([NSJSONSerialization isValidJSONObject:bodyParams]) {//validate it
        NSError* error = nil;
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:bodyParams options:NSJSONWritingPrettyPrinted error: &error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData 
 encoding:NSUTF8StringEncoding];
        NSURL* url = [NSURL URLWithString:@“my URL"];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
        [request setHTTPMethod:@"POST"];//use POST
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-length"];
        [request setHTTPBody:jsonData];//set data
        __block NSError *error1 = nil;

        //use async way to connect network
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error)
        {
            if ([data length]>0 && error == nil) {
                resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
                NSLog(@"resultsDictionary is %@",resultsDictionary);
               [self hideLoading];

            } else if ([data length]==0 && error ==nil) {
                NSLog(@" download data is null");
                [self hideLoading];
            } else if( error!=nil) {
                NSLog(@" error is %@",error);
                [self hideLoading];
            }
        }];
    }
}

【问题讨论】:

  • AFNetworking 使 Objective-C 的事情变得更容易。见stackoverflow.com/questions/21487184/…
  • 感谢您的建议,但我对这门语言还是很陌生,我想在迁移到图书馆之前了解如何以本地方式进行操作。
  • 有效请求。反对建议:尝试用 Objective-C 做一个简单的 GET 请求,你可能会发现它不值得处理原生网络。
  • 到目前为止,我已经使用 NSURLSession 和 NSURLSessionDataTask 完成了 GET 和 POST,它们看起来并没有那么糟糕。然而这些都是简单的例子。但是当它到达这些嵌套字典时,我不确定我是如何传递字典的。
  • 内容类型为“application/json”,正文只是纯文本表示。 AFJSONRequestSerializer 将接受一个 Objective-C 对象并将其序列化为 JSON。没有这个,也没有请求序列化器的概念,你将不得不自己做这一步。将您的对象序列化为 JSON 并将该 JSON 文本用作您的请求正文。

标签: ios objective-c http post


【解决方案1】:

似乎将 NSDictionary 转换为 JSON 是您的实际问题。见文档https://developer.apple.com/documentation/foundation/jsonserialization

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary
     options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData 
     encoding:NSUTF8StringEncoding];

【讨论】:

  • 谢谢@Mick,但我也在看这部分 NSDictionary *dict = @{@"key": value};从该标头 JSON 创建字典或嵌套字典是我需要帮助的第一部分。感谢您的帮助
  • 这样吗? *dict = @{@"key": @{@"nestedKey":nestedValue}}
  • 让我实现它并返回给你
  • 我用你推荐的代码更新了我的代码,但它仍然不起作用,它返回
  • resultsDictionary 是 { message = "Internal server error"; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 2016-01-25
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
相关资源
最近更新 更多