JSON data messed up in AFNetworking POST request

我们两清 提交于 2019-12-11 03:27:46

问题


I am sending a request with AFNetworking for Objective-C. When I NSLog the parameters this is the object I am sending:

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;
    }, ...

This is what the server receives.

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;},
...

It is as if it is taking each property of my object and creating a new object with it. The worse part is that it's taking the multiple objects that are in the array and putting all properties of all objects and turning them into separate object on the same depth of the array.

Here is the code I am using to send this off:

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)
{
}

I have not been able to figure out why this would be happening, and I am all out of guesses. If someone could point me in the right direction it would be very appreciated.

UPDATE

If I post a single object rather than an array of the objects it arrives at the server successfully.


回答1:


I was able to solve this issue by using an NSDictionary instead of an array. Each object I have has a unique key so I used that key for the NSDictionary like so:

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

That seems to have solved the issue.




回答2:


Take a look at my answer here: How can I POST an NSArray of NSDictionaries inside an NSDictionary without problems?

It solves all your problems.



来源:https://stackoverflow.com/questions/17475122/json-data-messed-up-in-afnetworking-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!