2010-04-05 6 views
6

Sto creando una richiesta JSON POST da Objective C utilizzando la libreria JSON in questo modo:iphone richiesta JSON POST al server Django crea QueryDict entro QueryDict

 
NSMutableURLRequest *request; 
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/", host, action]]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"]; 
NSMutableDictionary *requestDictionary = [[NSMutableDictionary alloc] init]; 
[requestDictionary setObject:[NSString stringWithString:@"12"] forKey:@"foo"]; 
[requestDictionary setObject:[NSString [email protected]"*"] forKey:@"bar"]; 

NSString *theBodyString = requestDictionary.JSONRepresentation; 
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding]; 
[request setHTTPBody:theBodyData]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

Quando ho letto questa richiesta nel mio Django visualizzare il debugger mostra ha preso l'intera stringa JSON e ne ha fatto la prima chiave del POST QueryDict:

 
POST QueryDict: QueryDict: {u'{"foo":"12","bar":"*"}': [u'']}> Error Could not resolve variable 

posso leggere il primo tasto e poi rianalizzare con JSON come un hack. Ma perché la stringa JSON non viene inviata correttamente?

risposta

0

mio mod crudele per aggirare il problema è:

 
hack_json_value = request.POST.keys()[0] 
hack_query_dict = json.loads(hack_json_value) 
foo = hack_query_dict['foo'] 
bar = hack_query_dict['bar'] 

Quindi questo mi permetterà di estrarre i due valori JSON con un passo in più sul lato server. Ma dovrebbe funzionare con un passo.

3

questo è il modo per elaborare una richiesta POST con i dati JSON:

def view_example(request): 
    data=simplejson.loads(request.raw_post_data) 

    #use the data 

    response = HttpResponse("OK") 
    response.status_code = 200 
    return response 
1

Ho già affrontato questo problema. Ho trovato una soluzione temporanea mentre leggevo il codice request.body. Presumo che tu abbia già importato la libreria json/simplejson. A mio avviso:

post = request.body 
post = simplejson.loads(post) 
foo = post["foo"] 

Questo blocco di codice mi ha aiutato a superare questione posta. Penso che la pubblicazione di querydict in request.POST non sia stata ancora sviluppata correttamente su NSMutableURLRequest.

Problemi correlati