我正在构建我的第一个iPhone应用程序,并且在尝试将json数据发布到我的MongoDB数据库时遇到了问题。
到目前为止,这是我的代码:
NSString *post = [NSString stringWithFormat:@"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://myURL/users"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(@"Reply: %@", theReply);
我在控制台中收到了这个回复:
2014-06-10 16:07:09.758 SocialEyez[2226:70b] Reply: {
"_id": "5397656dd7ec395c1b808230"
}
因此即使POST看起来很好,我的格式也有问题,这会阻止输入JSON数据。 我试图用一百种不同的方式格式化NSString,但似乎没什么用。
请帮帮我!!
编辑:
当我通过jQuery发送此请求时:
jQuery.post("http://site/users", { "name": "George Washington", "reputation": "pres", "phone_number": "1234" }, function (data, textStatus, jqXHR) { console.log("Post resposne:"); console.dir(data); console.log(textStatus); console.dir(jqXHR); });
我收到以下回复:
_id: "53978f4cd7ec395c1b808247"
name: "George Washington"
reputation: "pres"
phone_number: "1234"
答案 0 :(得分:1)
此示例假定发布数据应为JSON。
从字典创建JSON,让NSJSONSerialization
添加JSON语法。
// @"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"
// Create the dictionary
NSDictionary *postDict = @{@"name":@"blah", @"reputation":@"100", @"phone_number":@"1234"};
// Create the JSON data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];
// Just for this example: display the jsonData as an ASCII string
NSLog(@"jsonData as String: %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog输出:
jsonData: <7b226e61 6d65223a 22626c61 68222c22 72657075 74617469 6f6e223a 22313030 222c2270 686f6e65 5f6e756d 62657222 3a223132 3334227d>
jsonData as String: {"name":"blah","reputation":"100","phone_number":"1234"}