[英]parse json data
我需要将json传递给POST参数。 输入参数如下所示:
{ "type":"facebook",
"friends":[{ "id": "facebook id", "avatar": "url to avatar image", "first_name" : "first_name", "last_name" :"last_name"}] }
服务器响应错误指出它是错误的请求参数
Error - code: 400, message: {"status":"bad request","message":"undefined method `each' for #<String:0x00000005473e48>"}
当我在“ friends”部分准备JSON数据时,这可能是错误的。 你能帮我复习吗?
这是我的代码-
{
NSMutableArray *aFriends = [[NSMutableArray alloc] init];
int nCount = [[self savedSelIndexPath] count];
for (int i = 0; i < nCount && nCount > 0; i++)
{
NSIndexPath *path = [[self savedSelIndexPath] objectAtIndex:i];
NSDictionary *data = nil;
NSString *key = [[self keysArray] objectAtIndex:path.section];
NSArray *nameSection = [[self listContentDict] objectForKey:key];
data = [nameSection objectAtIndex:[path row]];
NSDictionary *dictFriends = [NSDictionary dictionaryWithObjectsAndKeys:
[data objectForKey:@"id"], @"id",
[data objectForKey:@"picture"], @"avatar",
[data objectForKey:@"first_name"], @"first_name",
[data objectForKey:@"last_name"], @"last_name",
nil];
[aFriends addObject:dictFriends];
dictFriends = nil;
}
DLog(@"aFriends: %@", aFriends);
NSDictionary *teamProfile = [[Global sharedGlobal] getPlistFile];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"facebook", @"type",
aFriends, @"friends", nil];
DLog(@"params: %@", params);
NSString *sPath = [NSString stringWithFormat:@"/users/%@/friends", [teamProfile valueForKey:@"userId"]];
NSMutableURLRequest *request = [[[Global sharedGlobal] httpClient] requestWithMethod:@"POST" path:sPath parameters:params];
DLog(@"request: %@", request);
….
[aFriends release];
}
如果要将JSON传递到服务器,则必须像这样进行设置:
NSMutableURLRequest *networkRequest;
networkRequest = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:[networkServerAddress stringByAppendingString:@""]]];
send = [[json objectAtIndex:i] dataUsingEncoding:NSUTF8StringEncoding];
//Set the headers appropriately
[networkRequest setHTTPMethod:@"POST"];
[networkRequest setValue:@"application/json"
forHTTPHeaderField: @"Content-type"];
[networkRequest setValue:[NSString stringWithFormat:@"%d", [send length]]
forHTTPHeaderField:@"Content-length"];
[networkRequest setValue:@"application/json"
forHTTPHeaderField:@"Accept"];
//Set the body to the json encoded string
[networkRequest setHTTPBody:send];
发送必须是NSData,而不是字典。 如果要这样做,必须首先解析字典。 有很多不错的JSON解析器/编写器,我个人喜欢并使用SBJson 。 使用SBJson,您可以执行以下操作:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSData *dataToSend = [writer dataWithObject:data];
我不确定我是否理解您的要求,但是您说您需要将数据编码为JSON,并且看不到任何用于参数的JSON编码指令。 您只是通过了NSDictionary * dictFriends ...是否正确?
再见!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.