11

でjsonを投稿する方法の例を探していAFHTTPClientます。を受け取り、NSDictionaryAFJSONEncode メソッドが を返す postPath メソッドがあることがわかりますNSData。オブジェクトを にシリアル化する簡単な方法はありますNSDictionaryか、または jsonkit を使用する簡単な方法はありますか?

オブジェクトをjsonとしてREST APIに投稿するだけです。

更新:辞書を渡そうとしましたが、ネストされた配列をシリアル化すると壊れるようです。

たとえば、オブジェクトがある場合:

Post* p = [[Post alloc] init];
p.uname = @"mike";
p.likes =[NSNumber numberWithInt:1];
p.geo = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:37.78583], [NSNumber numberWithFloat:-122.406417], nil ];
p.place = @"New York City";
p.caption = @"A test caption";
p.date = [NSDate date];

who's get 辞書には次のようなデータがあります。

{
    caption = "A test caption";
    date = "2011-12-13 17:58:37 +0000";
    geo =     (
        "37.78583",
        "-122.4064"
    );
    likes = 1;
    place = "New York City";

}

シリアル化は完全に失敗するか、geo が配列としてシリアル化されず、次のような文字列リテラルとしてシリアル化されます。("37.78583", "-122.4064");

4

3 に答える 3

26

JSON REST API に投稿する場合、オブジェクト プロパティから JSON キーへの特定のマッピングが必要ですよね? つまり、サーバーは特定の名前付きフィールドに特定の情報を期待しています。

そのため、API で使用されるキーとそれに対応する値を使用してNSDictionaryorを作成する必要があります。NSMutableDictionary次に、その辞書をparametersの任意のリクエスト メソッドの引数に渡すだけAFHTTPClientです。クライアントのparameterEncodingプロパティが に設定されている場合AFJSONParameterEncoding、リクエストの本文は自動的に JSON としてエンコードされます。

于 2011-12-13T15:31:32.007 に答える
7

これを行う最善かつ簡単な方法は、AFHTTPClient をサブクラス化することです。

このコード スニペットを使用します

MBHTTP クライアント

#define YOUR_BASE_PATH @"http://sample.com"
#define YOUR_URL @"post.json"
#define ERROR_DOMAIN @"com.sample.url.error"

/**************************************************************************************************/
#pragma mark - Life and Birth

+ (id)sharedHTTPClient
{
    static dispatch_once_t pred = 0;
    __strong static id __httpClient = nil;
    dispatch_once(&pred, ^{
        __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:YOUR_BASE_PATH]];
        [__httpClient setParameterEncoding:AFJSONParameterEncoding];
        [__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
        //[__httpClient setAuthorizationHeaderWithUsername:@"" password:@""];
    });
    return __httpClient;
}

/**************************************************************************************************/
#pragma mark - Custom requests

- (void) post<#Objects#>:(NSArray*)objects
success:(void (^)(AFHTTPRequestOperation *request, NSArray *objects))success
failure:(void (^)(AFHTTPRequestOperation *request, NSError *error))failure
{
    [self postPath:YOUR_URL
       parameters:objects
          success:^(AFHTTPRequestOperation *request, id JSON){
              NSLog(@"getPath request: %@", request.request.URL);

              if(JSON && [JSON isKindOfClass:[NSArray class]])
              {
                  if(success) {
                      success(request,objects);
                  }
              }
              else {
                  NSError *error = [NSError errorWithDomain:ERROR_DOMAIN code:1 userInfo:nil];
                  if(failure) {
                      failure(request,error);
                  }
              }
          }
          failure:failure];
}

次に、コードで呼び出すだけです

[[MBHTTPClient sharedHTTPClient]  post<#Objects#>:objects
                                          success:^(AFHTTPRequestOperation *request, NSArray *objects) {
    NSLog("OK");
}
                                          failure:(AFHTTPRequestOperation *request, NSError *error){
    NSLog("NOK %@",error);
}

オブジェクトは NSArray (NSDictonary に変更できます) であり、JSON 形式でエンコードされます

于 2011-12-12T15:10:47.517 に答える
0
 - (NSMutableURLRequest *)requestByPostWithNSArrayToJSONArray:(NSArray *)parameters
{
    NSURL *url = [NSURL URLWithString:@"" relativeToURL:self.baseURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setAllHTTPHeaderFields:self.defaultHeaders];

    if (parameters)
    {
            NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
            NSError *error = nil;

            [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wassign-enum"
            [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]];
#pragma clang diagnostic pop

            if (error) {
                NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
            }
    }

    return request;
}
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL         URLWithString:URL_REGISTER_DEVICE]];
NSArray *array = @[@"hello", @"world"];
NSMutableURLRequest *request = [httpClient requestByPostWithNSArrayToJSONArray:array];


AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
    NSLog(@"network operation succ");

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"network operation fail");

}];

[operation start];
于 2013-08-27T09:21:14.550 に答える