2013-02-13 118 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