我試圖通過POST將參數發送到我的服務器,它一般工作,但我無法弄清楚如何發送包含數組作爲參數的JSON 。以下是我試過的:AFNetworking在發送請求的JSON參數中發送數組
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:myURL]];
NSMutableArray *objectsInCart = [NSMutableArray arrayWithCapacity:[_cart count]];
for(NSDictionary *dict in _cart)
{
NSObject *object = [dict objectForKey:@"object"];
NSDictionary *objectDict = @{@"product_id": [NSString stringWithFormat:@"%d",[object productID]],
@"quantity": [NSString stringWithFormat:@"%d", [[dict objectForKey:@"count"] intValue]],
@"store_id": [NSString stringWithFormat:@"%d", [Store getStoreID]],
@"price": [NSString stringWithFormat:@"%.2f", [object price]]};
[objectsInCart addObject:objectDict];
}
NSError *error = nil;
NSString *cartJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];
if(error)
{
NSLog(@"Error serializing cart to JSON: %@", [error description]);
return;
}
NSDictionary *parameters = @{@"status": @"SUBMITTED",
@"orders": cartJSON};
NSMutableURLRequest *orderRequest = [httpClient requestWithMethod:@"POST"
path:@"/app/carts"
parameters:parameters];
AFJSONRequestOperation *JSONOperation = [[AFJSONRequestOperation alloc] initWithRequest:orderRequest];
但是,發送此JSON時出現錯誤。任何建議都非常感謝!
我不知道服務器期望什麼,但通常情況下,JSON中的每個項目都有一個密鑰,包括數組。你現在只是發送數組,沒有密鑰。試試'NSString * cartJSON = @''products':%@「,[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding]; – dirkgroten
如果你看'參數'字典,數組的關鍵是'@「命令」' – Mason
好吧,我不好,我錯過了。你看過通過線路發送的實際數據嗎?我非常重視查爾斯代理這樣的應用程序,以攔截從我的應用程序到外部服務器的所有流量。 – dirkgroten