Mon*_*key 11 jsonkit afnetworking
寻找一个如何发布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];
Run Code Online (Sandbox Code Playgroud)
谁得到字典有如下数据:
{
caption = "A test caption";
date = "2011-12-13 17:58:37 +0000";
geo = (
"37.78583",
"-122.4064"
);
likes = 1;
place = "New York City";
}
Run Code Online (Sandbox Code Playgroud)
序列化将直接失败或geo不会被序列化为数组,而是像字符串文字一样 ("37.78583", "-122.4064");
mat*_*ttt 26
如果您要发布到JSON REST API,那么应该存在从object属性到JSON密钥的特定映射,对吧?也就是说,服务器期望某些命名字段中的某些信息.
所以你想要做的是构建一个NSDictionary或NSMutableDictionary使用API中使用的密钥及其相应的值.然后,只需将该字典传递给parameters任何请求方法的参数AFHTTPClient.如果parameterEncoding客户端的属性设置为AFJSONParameterEncoding,则请求的主体将自动编码为JSON.
最好和最简单的方法是将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];
}
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中调用
[[MBHTTPClient sharedHTTPClient] post<#Objects#>:objects
success:^(AFHTTPRequestOperation *request, NSArray *objects) {
NSLog("OK");
}
failure:(AFHTTPRequestOperation *request, NSError *error){
NSLog("NOK %@",error);
}
Run Code Online (Sandbox Code Playgroud)
对象是NSArray(您可以将其更改为NSDictonary)并将以JSON格式进行编码
| 归档时间: |
|
| 查看次数: |
20407 次 |
| 最近记录: |