2013-08-20 16 views
6

Sto provando a inviare parametri al mio server tramite POST, e funziona in generale, ma non riesco a capire come inviare JSON che contiene un array come uno dei parametri . Ecco cosa ho provato:AFNetworking send array nei parametri JSON di richiesta post

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]; 

Tuttavia, si riceve un errore durante l'invio di questo JSON. Ogni suggerimento è molto apprezzato!

+0

Non so cosa si aspetta il server, ma in genere, ogni elemento in JSON ha una chiave, incluso l'array. Stai semplicemente inviando l'array ora, senza una chiave per farlo. Prova 'NSString * cartJSON = @" 'prodotti':% @ ", [[NSString alloc] initWithData: [NSJSONSerialization dataWithJSONObject: objectsInCart options: NSJSONWritingPrettyStampa di errore: & error] encoding: NSUTF8StringEncoding]; – dirkgroten

+0

Se si guarda il dizionario 'parameters', la chiave per l'array è' @ "orders" ' – Mason

+0

ok, il mio male mi è mancato. Hai guardato i dati effettivi inviati sulla linea? Sono arrivato a valutare un'app come il proxy Charles per intercettare tutto il traffico dalla mia app ai server esterni. – dirkgroten

risposta

9

Non vedo dove stai specificando che si desidera inviare JSON, quindi scommetto che si sta inviando modulo URL dei parametri di codifica, che va in questo modo, in base alla documentazione AFHTTPClient:

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.

Se il server è in effetti si aspetta di inviare JSON, aggiungere questo sulla seconda riga per dire che 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; 

si potrebbe quindi rimuovere la chiamata a NSJSONSerialization e appena messo objectsInCart nella parameters dic nale.

Una nota a margine: è normale sottoclasse AFHTTPRequestOperationManager o AFHTTPSessionManager (AFNetworking 2.0) o AFHTTPClient (AFNetworking 1.0) e mettere questo tipo di configurazione nel metodo initWithBaseURL:. (Probabilmente non si desidera creare un nuovo client per ogni richiesta.)

+0

Gah sì, l'ho trovato prima, avrei dovuto aggiornare il post. Grazie! – Mason

Problemi correlati