开发者

iphone Json POST request to Django server creates QueryDict within QueryDict

I'm creating a JSON POST request from Objective C using the JSON library like so:

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"];
[requestDi开发者_开发知识库ctionary setObject:[NSString stringWithString@"*"] forKey:@"bar"];

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

When I read this request in my Django view the debugger shows it took the entire JSON string and made it the first key of the POST QueryDict:

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

I can read the first key and then reparse using JSON as a hack. But why is the JSON string not getting sent correctly?


This is the way to process a POST request with json data:

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

    #use the data

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


I have already dealt with this issue. I found a temporary solution as reading the request.body dict. I assume you have imported the json/simplejson library already. In my view:

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

This code block helped me to pass post issue. I think posting querydict in request.POST has not properly developed on NSMutableURLRequest yet.


My cruel hack to work around my problem is:

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

So this will allow me to extract the two JSON values with an extra step on server side. But it should work with one step.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜