我正在使用JSON库从Objective C创建一个JSON POST请求,如下所示:
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 stringWithString@"*"] forKey:@"bar"];
NSString *theBodyString = requestDictionary.JSONRepresentation;
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:theBodyData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
当我在Django视图中读取此请求时,调试器显示它占用了整个JSON字符串并使其成为POST QueryDict的第一个键:
POST QueryDict: QueryDict: {u'{"foo":"12","bar":"*"}': [u'']}> Error Could not resolve variable
我可以读取第一个键,然后使用JSON作为黑客重新解析 . 但为什么JSON字符串没有正确发送?
3 回答
我解决我的问题的残酷黑客是:
所以这将允许我通过服务器端的额外步骤提取两个JSON值 . 但它应该一步到位 .
这是使用json数据处理POST请求的方法:
我已经处理过这个问题 . 我在阅读
request.body
字典时找到了一个临时解决方案 . 我假设你已经导入了json/simplejson
库 . 在我看来:此代码块帮助我传递帖子问题 . 我认为在
request.POST
中发布querydict
尚未在NSMutableURLRequest
上正确开发 .