11

寻找如何发布 json 的示例AFHTTPClient。我看到有一个 postPath 方法需要一个NSDictionary,而 AFJSONEncode 方法返回一个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];

谁的字典有如下数据:

{
    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然后,只需将该字典传递parametersAFHTTPClient. 如果parameterEncoding客户端的属性设置为AFJSONParameterEncoding,则请求的正文将自动编码为 JSON。

于 2011-12-13T15:31:32.007 回答
7

最好和最简单的方法是继承 AFHTTPClient。

使用此代码段

MBHTTPClient

#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);
}

objects 是一个 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 回答