寻找如何使用AFHTTPClient
发布json的示例。我看到有一个postPath方法接受NSDictionary
并且AFJSONEncode方法返回NSData
。有没有一种简单的方法可以将对象序列化为NSDictionary
,还是使用jsonkit更简单?
我只需要将对象作为json发布到REST API。
UPDATE:所以我尝试传递字典,但似乎在序列化嵌套数组时中断了。
例如,如果我有一个对象:
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");
答案 0 :(得分:26)
如果您要发布到JSON REST API,那么应该存在从对象属性到JSON密钥的特定映射,对吧?也就是说,服务器期望某些命名字段中的某些信息。
因此,您要做的是使用API中使用的密钥及其对应的值构建NSDictionary
或NSMutableDictionary
。然后,只需将该字典传递到parameters
中任何请求方法的AFHTTPClient
参数。如果客户端的parameterEncoding
属性设置为AFJSONParameterEncoding
,则请求正文将自动编码为JSON。
答案 1 :(得分: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);
}
对象是NSArray(您可以将其更改为NSDictonary)并将以JSON格式进行编码
答案 2 :(得分: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];