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

0

JSONKitやRESTKitなどのフレームワークを使用しようとしましたか?RESTKitは、JSONとのWebサービス通信に特別に使用され、内部でJSONKitと相互のパーサーを使用します。私はこれがあなたの問題と多分将来の問題を解決すると思います;)

于 2012-06-05T06:07:41.560 に答える
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

リクエストの本文として 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 に答える