我正在使用 AFNetworking for Objective-C 发送请求。当我 NSLog 参数时,这是我发送的对象:
games = (
{
id = 50;
p = 8;
ts = 0;
tt = ();
tw = 0;
ys = 35150;
yt = {
156424496 = "37.416669";
156609008 = "56.661210";
....
252846816 = "7.075133";
252856944 = "61.329850";
};
yw = 0;
}, ...
这是服务器接收到的内容。
games = (
{id = 50;},
{p = 8;},
{ts = 0;},
{tw = 0;},
{ys = 35150;},
{
yt = {156424496 = "37.416669";};
},
{
yt = {156609008 = "56.661210";};
},
...
{
yt = {252846816 = "7.075133";};
},
{
yt = {252856944 = "61.329850";};
},
{yw = 0;},
...
就好像它正在获取我的对象的每个属性并用它创建一个新对象。更糟糕的是,它获取数组中的多个对象,并将所有对象的所有属性放入数组的相同深度上,并将它们转换为单独的对象。
这是我用来发送此邮件的代码:
NSArray *games = [ResourceManager getAllGames];
NSMutableArray *gamesArray = [[NSMutableArray alloc] initWithCapacity:[games count]];
for(Game *g in games)
{
[gamesArray addObject:[g toDictionary]];
}
User *user = [ResourceManager getUser];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:gamesArray, @"games", user.id, @"user_id", nil];
NSLog(@"PARAMS: %@", params); <- this is the first block of code above
[self postPath:API_SYNC_GAMES_URL parameters:params success:^(AFHTTPRequestOperation *operation, id JSON)
{
}
我一直无法弄清楚为什么会发生这种情况,而且我完全无法猜测。如果有人能指出我正确的方向,我将不胜感激。
更新
如果我发布单个对象
而不是对象数组,它会成功到达服务器。
最佳答案
我能够通过使用 NSDictionary 而不是数组来解决这个问题。我拥有的每个对象都有一个唯一的键,因此我将该键用于 NSDictionary,如下所示:
NSMutableDictionary *gamesArray = [[NSMutableDictionary alloc]
initWithCapacity:[games count]];
for(Game *g in games)
{
[gamesArray setObject:[g toDictionary]
forKey:[NSString stringWithFormat:@"%@", g.id]];
}
这似乎已经解决了问题。
关于objective-c - AFNetworking POST 请求中的 JSON 数据困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17475122/