1

到目前为止,我一直在使用objective-c 中的json(使用SBJson 类)从restAPI 接收数据。我现在正在尝试发送帖子数据,但我没有这方面的经验。原始主体如下所示:

  //http://www.myapi.com/api/user=123
  "Username": "foo",
  "Title": null,
  "FirstName": "Nick",
  "MiddleInitial": null,
  "LastName": "Foos",
  "Suffix": null,
  "Gender": "M",
  "Survey": {
         "Height": "4'.1\"",
         "Weight": 100,
               }

这种数据的最佳方式是什么?

4

2 回答 2

1

您需要一个包含上述每个键条目的字典,然后将字典转换为 JSON 字符串。请注意,Survey 键本身就是一个字典。像这样的东西。

NSMutableDictionary *dictJson= [NSMutableDictionary dictionary];
[dictJson setObject:@"foo" forKey:@"Username"];
...
[dictJson setObject:dictSurvey forKey:@"Survey"];

//convert the dictinary to a JSON string
NSError *error = nil;
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *result = [jsonWriter stringWithObject:dictJson error:&error];
[jsonWriter release];
于 2013-02-13T16:45:52.550 回答
1

假设您有一个字符串中的帖子数据,称为myJSONString. (从 Objective-C 集合到 json 也很简单。看起来@Joel 回答了这个问题)。

// build the request
NSURL *url = [NSURL urlWithString:@"http://www.mywebservice.com/user"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";

// build the request body
NSData *postData = [myJSONString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// run the request
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if (!error) {
                               // yay
                           } else {
                               // log the error
                           }
                       }];
于 2013-02-13T16:49:00.547 回答