2013-08-20 7 views
6

POST를 통해 서버에 매개 변수를 보내려고하는데 일반적으로 작동하지만 배열을 매개 변수 중 하나로 포함하는 JSON을 보내는 방법을 알 수 없습니다 . 여기에 내가 무엇을 시도했다입니다 :POST 요청의 JSON 매개 변수로 AFNetworking 배열 보내기

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을 보낼 때이 오류가 발생합니다. 어떤 제안이라도 대단히 감사합니다!

+0

서버가 예상하는 내용을 알지 못하지만 일반적으로 JSON의 모든 항목에는 배열을 포함한 키가 있습니다. 이제 키를 사용하지 않고 배열을 전송하는 것입니다. "NSString * cartJSON = @" 'products': % @ ", [[NSString alloc] initWithData : [NSJSONSerialization dataWithJSONObject : objectsInCart 옵션 : NSJSONWritingPrettyPrinted 오류 : & 오류] 인코딩 : NSUTF8StringEncoding]을 시도하십시오. – dirkgroten

+0

'parameters' 사전을 보면 배열의 키가'@ "orders"' – Mason

+0

입니다. 선을 통해 전송되는 실제 데이터를 살펴 보았습니까? 필자는 찰스 프록시와 같은 앱의 가치를 높이기 위해 내 앱에서 외부 서버로 보내는 모든 트래픽을 차단했습니다. – dirkgroten

답변

9

나는 내가 AFHTTPClient 문서에 따라,이 같은 간다 양식 URL 매개 변수 인코딩을 보내는 걸거야 당신은 당신이 JSON을 게시 할 지정하고 어디에 있는지, 그렇게하지 않습니다

If a query string pair has a an NSArray for its value, each member of the array will be represented in the format field[]=value1&field[]=value2 . Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the -description method. The constructed query string does not include the ? character used to delimit the query component.

서버가 실제로 JSON을 게시을 기대하는 경우

, 즉 AFNetworking 말 두 번째 줄에 추가 :

// AFNetworking 1.0 
// httpClient is a subclass of AFHTTPClient 
httpClient.parameterEncoding = AFJSONParameterEncoding; 

// AFNetworking 2.0 
// httpClient is a subclass of AFHTTPRequestOperationManager or AFHTTPSessionManager 
httpClient.requestSerializer = AFJSONRequestSerializer; 

그런 다음 NSJSONSerialization에 전화를 제거 할 그냥 parameters DIC에 objectsInCart를 넣어 .

측면 참고 : AFHTTPRequestOperationManager 또는 AFHTTPSessionManager (AFNetworking 2.0) 또는 AFHTTPClient (AFNetworking 1.0)를 서브 클래 싱하고 initWithBaseURL: 방법이 유형의 구성을 넣어 정상입니다. (모든 요청에 ​​대해 새로운 클라이언트를 시작하고 싶지는 않을 것입니다.)

+0

Gah yeah 나는 이것을 이전에 발견 했으므로 게시물을 업데이트해야합니다. 감사! – Mason

관련 문제