0

I have successfully created a method which connects to my web service and POSTS a string and receives a string response. However, I am now trying to POST a JSON dictionary created using NSJSONSerialization. However, Xcode is giving me an error. I have tried to convert my initial code. Relevant lines below...

NSData* loginDataJSON = [NSJSONSerialization dataWithJSONObject:loginDataDictionary options:NSJSONWritingPrettyPrinted error:&error];
[request setValue:loginDataJSON forHTTPHeaderField:@"loginDataJSON"];
[request setHTTPBody:[loginDataJSON dataUsingEncoding:NSUTF8StringEncoding]];

The second line heres complains that I am using NSData where an NSString is required. The third line complains that loginDataJSON may not respond to dataUsingEnconding

I seem to be forcing an NSData object (because that what NSJSONSerialization gives me) where it cannot be used. Am I best trying to convert the JSON into a string to use with my existing request code, or should/can I change my request code to accept NSData as opposed to an NSString?

4

4 回答 4

1

试试这个代码:

let body = NSMutableDictionary()
body.setValue("myString" forKey: "stringType")
body.setValue(data?.base64EncodedString(options: .lineLength64Characters) forKey: "dataType")

通过这种方式,您可以在字典中同时拥有数据和字符串。这里'data?.base64EncodedString(options: .lineLength64Characters)'返回一个带有 base64 编码的字符串。因此,您的字典仅包含字符串,并且在服务器端您必须将其转换回数据。

希望它能解决你的问题。

于 2018-08-24T21:35:19.623 回答
0

提出一个可变的请求并

 [request setHTTPBodyWithString:myMessageJSON];

其中方法如下:

- (void)setHTTPBodyWithString:(NSString *)body {
    NSData *bodyData = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [self setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [self setHTTPBody:bodyData];
}
于 2012-06-05T06:08:43.047 回答
0

您是否尝试过使用 JSONKit 或 RESTKit 等框架?RESTKit 专门用于与 JSON 的 web 服务通信,内部使用 JSONKit 和另一个解析器。我认为这将解决您的问题,也许是未来的问题;)

于 2012-06-05T06:07:41.560 回答
0

您需要将 JSON 作为请求的主体发送,并且可能设置内容类型和内容长度:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [loginDataJSON length]] forHTTPHeaderField:@"content-length"];
[request setHTTPBody:loginDataJSON];
于 2012-06-05T08:14:30.367 回答