2013-02-13 134 views
1

到目前为止,我一直在使用的是在objective-c中使用json(使用SBJson类)从restAPI接收数据。我现在试图发送发布数据,但我没有经验。原始的身体看起来像下面这样:json数据自定义http请求

//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, 
       } 

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

回答

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 
          } 
         }]; 
+0

谢谢你的回应。我有一个问题。我还必须发送一个唯一的密钥作为客户头。我怎么会发送这个呢? – bardockyo 2013-02-13 17:17:40

+0

当然。 [request setValue:@“value”forHTTPHeaderField:@“key”]; – danh 2013-02-13 17:38:43

1

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

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]; 
+0

非常感谢回复。我不知道如何接近调查字典。这将确定工作。 – bardockyo 2013-02-13 17:18:16