【问题标题】:JSON data messed up in AFNetworking POST requestAFNetworking POST 请求中的 JSON 数据混乱
【发布时间】:2013-07-04 16:47:20
【问题描述】:

我正在使用 AFNetworking 为 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)
{
}

我无法弄清楚为什么会发生这种情况,而且我完全没有猜测。如果有人能指出我正确的方向,将不胜感激。

更新

如果我发布 single object 而不是对象数组,它会成功到达服务器。

【问题讨论】:

  • 键值对不应该用逗号分隔吗?
  • 如何将对象序列化为 JSON?
  • 这是我传递给 AFNetworking 请求的 NSDictionaries 的 NSArray
  • @CraigOtis 我更新了问题以准确显示我在做什么
  • @brenjt 你能调试postPath: 方法来确定字典实际上是如何被序列化的吗?

标签: objective-c json afnetworking


【解决方案1】:

我能够通过使用 NSDictionary 而不是数组来解决这个问题。我拥有的每个对象都有一个唯一的键,所以我将这个键用于 NSDictionary,如下所示:

NSMutableDictionary *gamesArray = [[NSMutableDictionary alloc] 
                                          initWithCapacity:[games count]];
for(Game *g in games)
{
    [gamesArray setObject:[g toDictionary] 
                   forKey:[NSString stringWithFormat:@"%@", g.id]];
}

这似乎解决了问题。

【讨论】:

    【解决方案2】:

    在这里看看我的回答: How can I POST an NSArray of NSDictionaries inside an NSDictionary without problems?

    它解决了你所有的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多